UDP network programming

Posted by jtrost on Mon, 20 Dec 2021 14:19:32 +0100

catalogue

1 byte order

How to determine the byte order of the current byte

2-byte order conversion function

3 ip address translation function

inet_pton / / String ip address to integer data

inet_ntop / / convert integer data to string format ip address

inet_addr() and inet_ntoa()

4 UDP overview

5 network programming interface socket

6 UDP programming C/S architecture

7 create socket

8 ipv4 socket address structure

9 send data - sendto function

10 send a message to the network debugging assistant

Writing client code under ubnunt

1 byte order

Refers to the storage order of multi byte data storage

Host byte order HBO: different machines have different HBO, which is related to CPU design. The order of data is determined by CPU and has nothing to do with the operating system. (the big and small end modes are related to CPU design and independent of operating system)

For example, under Intel x86 architecture, the number of short type 0x1234 is 34 12, and the number of int type 0x12345678 is 78 56 34 12
For example, under the IBM power PC structure, the short type number 0x1234 represents 12 34, and the int type number 0x12345678 represents 12 34 56 78


classification
Small end format: store low byte data in low address
Big end format: store high byte data in address

LSB: the lower address number is 0x01
MSB: the high address number is 0x04

For example: int i = 0x12345678
12 is high byte order (near 0x)
78 is low byte order (0x)

How to determine the byte order of the current byte

//Used to determine the byte order of the current byte
#include <stdio.h>

union un
{//Common body
    int a; 
    char b;
};

int main(int argc, char const *argv[])
{
    union un myun;
    myun.a = 0x1234567;
    printf("a = %#x\n", myun.a);
    printf("b = %#x\n", myun.b);

    if(myun.b == 0x78)
    {
        printf("Small end storage\n");
    }
    else
    {
        printf("Big end storage\n");
    }
    return 0;
}

2-byte order conversion function

characteristic:
1. The network protocol specifies the communication byte order - big end
2. Byte order needs to be considered only in multi byte data processing
3. When processes running on the same computer communicate with each other, byte order is generally not considered
4. The communication between heterogeneous computers needs to convert their own byte order into network byte order

When byte order conversion is required, a specific byte order conversion function is generally called

host --> network//Convert host byte order to network byte order
#include<arpa/inet.h>
1--htonl
2--htons
htonl For 32 bits, 4 bytes
htons For 16 bits, 2 bytes


network -->host//Convert network byte order to host byte order
3 --ntohl
4 --ntohs

#include <stdio.h>
#include <arpa/inet.h>
 
int main(int argc, char const *argv[])
{
    int a = 0x12345678;
    short b = 0x1234;

    printf("%#x\n",htonl(a));
    printf("%#x\n",htons(b));
    
    return 0;
}

3 ip address translation function

For human identification, the ip address is a dotted decimal string type

During computer / network identification, ip address is unsigned integer data

So it needs to be transformed

inet_pton / / String ip address to integer data

#include <stdio.h>
#include <arpa/inet.h>

int main(int argc, char const *argv[])
{
    char ip_str[]="192.138.3.103";
    unsigned int ip_int = 0;
    unsigned char *ip_p = NULL;

    //Convert dotted decimal ip address to 32-bit unsigned integer data
    inet_pton(AF_INET,ip_str,&ip_int);

    printf("ip_int = %d\n",ip_int);

    ip_p = (char *)&ip_int;
    printf("in_uint = %d,%d,%d,%d\n",*ip_p,*(ip_p+1),*(ip_p+2),*(ip_p+3));
    
    return 0;
}

inet_ntop / / convert integer data to string format ip address

#include <stdio.h>
#include <arpa/inet.h>

int main(int argc, char const *argv[])
{
    unsigned char ip_int[] = {192, 168, 3, 103};
    char ip_str[16] = "";
    //Convert 32-bit unsigned integer data into dotted decimal ip address
    inet_ntop(AF_INET,&ip_int,ip_str,16);

    printf("ip_s = %s\n",ip_str);

    return 0;
}

inet_addr() and inet_ntoa()

inet_addr: convert dotted decimal ip addresses into integer data, which can only be used for conversion between ipv4 addresses

inet_ntoa: divide integer data conversion sites into decimal ip addresses, which can only be used for conversion between ipv4 addresses

4 UDP overview

Face connectionless; No connection established (more efficient than TCP); limited transmission 64k; unreliable protocol (simpler than TCP); transport layer protocol

Function:
Provide process communication on different hosts

characteristic
1. There is no need to establish a link before sending data, which is slightly faster than TCP
2. The order of packets is not checked
3. There is no error detection and retransmission mechanism

  • Simple request / reply applications can use UDP
  • UDP should not be used for mass data transmission
  • Broadcast and multicast applications must use UDP


Service object:
It is mainly used for "query answer" service
For example: NFS (network file system), RTP (streaming media), DNS (domain name resolution)

General voice and video calls use udp to communicate

5 network programming interface socket

Network communication is to solve the communication between different host processes
The primary problem is network process identification
And the identification of multiple protocols

With the wide application of UNIX and UNIX like operating system, socket has become the most popular network program development interface

socket function
Provides communication between processes on different hosts
socket features
Socket is also called "socket"
Is a file descriptor that represents an endpoint of a communication pipeline
Similar to the operation of files, you can use read, wirete, close and other functions to collect and send network data to socket s
Get the socket (descriptor) method and call the socket function

socket classification
 SOCK_STREAM, streaming socket, for TCP
SOCK_DGRAM, datagram socket, for UDP
 SOCK_RAW, raw socket. This type is required for protocol operations at other levels

6 UDP programming C/S architecture

7 create socket

#include <sys/socket.h>

int socket(int domain, int type, int protocol)
Function: create a for network communication socket socket
 Parameters:
  domain:Communication domain, protocol family
    AF_UNIX Local communication
    AF_INET ipv4 Network protocol
    AF_INET6 ipv6 Network protocol
    AF_PACKET Underlying interface
 type:socket classification
      SOCK_STREAM,Streaming socket for TCP
       SOCK_DGRAM,Datagram socket for UDP
      SOCK_RAW,Raw socket. This type is required for protocol operations at other levels
  protocol: Additional protocol, set to 0 if not required
 Return value:
   Success: file descriptor
   Failed:-1
 characteristic:
 When creating sockets, the system does not allocate ports
 The default attribute of the created socket is active, that is, actively initiating service requests; When you are a server, you often need to modify the bit passivity

#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
    //Create a socket using the socket function
    //Create a socket for UDP network programming
    int sockfd;
    if((sockfd = socket(AF_INET,SOCK_DGRAM,0))==-1)
    { 
        perror("fail tp socket");
        exit(1);
    }

    printf("sockfd = %d\n",sockfd);
    return 0;
}

8 ipv4 socket address structure

#include <netinet/in.h>

/* Internet address.  */
typedef uint32_t in_addr_t;
struct in_addr
  {
    in_addr_t s_addr;//IP address
  };

/* Structure describing an Internet socket address.  */
struct sockaddr_in
  {
    __SOCKADDR_COMMON (sin_);       //Protocol family
    in_port_t sin_port;			/* Port number. Port number */
    struct in_addr sin_addr;		/* Internet address. IPaddress */

    /* Pad to size of `struct sockaddr'.  */
    unsigned char sin_zero[sizeof (struct sockaddr) -
			   __SOCKADDR_COMMON_SIZE -
			   sizeof (in_port_t) -
			   sizeof (struct in_addr)];
  };

In order for addresses of different formats to be passed into socket functions, addresses must be cast into bit general socket address structures

9 send data - sendto function

10 send a message to the network debugging assistant

ps: you need to use the network debugging assistant used under windows

The ip address cannot be set arbitrarily. It must be the ip address of the current windows

Writing client code under ubnunt

#include <stdio.h> //printf
#include <stdlib.h>//exit
#include <sys/types.h>
#include <sys/socket.h>//socket
#include <netinet/in.h>//sockaddr_in
#include <arpa/inet.h>//hton inet_addr
#include <unistd.h> //close
#include <string.h>

#define N 512
int main(int argc, char const *argv[])
{
    //The first step is to create a socket
    int sockfd;
    if((sockfd = socket(AF_INET,SOCK_DGRAM,0))==-1)
    { 
        perror("fail tp socket");
        exit(1);
    }
    printf("sockfd = %d\n",sockfd);
    //The second step is to fill in the network server network information structure, sockaddr_in
    struct sockaddr_in serveraddr;
    socklen_t addrlen = sizeof(serveraddr);
    serveraddr.sin_family = AF_INET;//Protocol family, ipv4
    serveraddr.sin_addr.s_addr = inet_addr("172.31.192.1");//ip address
    serveraddr.sin_port = htons(8080);//sin_port is uint16, so htons is used
    //Step 3: send data
    char buf[N] = "";
    while (1)
    {
        fgets(buf,N,stdin);
        buf[strlen(buf)-1] = '\0';//Convert \ n in buf string to \ 0
        if(sendto(sockfd,buf,N,0,(struct sockaddr *)&serveraddr,addrlen) == -1)
        {
            perror("fail tp sendto");
            exit(1);
        }
    }
    
    //Step 4: close the socket file descriptor
    close(sockfd);

    return 0;
}

  • Modify it to be more general. After gcc, enter it in the terminal/ a.out ip port

#include <stdio.h> //printf
#include <stdlib.h>//exit
#include <sys/types.h>
#include <sys/socket.h>//socket
#include <netinet/in.h>//sockaddr_in
#include <arpa/inet.h>//hton inet_addr
#include <unistd.h> //close
#include <string.h>

#define N 512
int main(int argc, char const *argv[])
{
    if(argc<3)
    {
        fprintf(stderr,"Usage: %s ip port\n",argv[0]);
        exit(1);
    }
    //The first step is to create a socket
    int sockfd;
    if((sockfd = socket(AF_INET,SOCK_DGRAM,0))==-1)
    { 
        perror("fail tp socket");
        exit(1);
    }
    printf("sockfd = %d\n",sockfd);
    //The second step is to fill in the network server network information structure, sockaddr_in
    struct sockaddr_in serveraddr;
    socklen_t addrlen = sizeof(serveraddr);
    serveraddr.sin_family = AF_INET;//Protocol family, ipv4
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);//ip address
    serveraddr.sin_port = htons(atoi(argv[2]));//sin_port is uint16, so htons is used
    //Step 3: send data
    char buf[N] = "";
    while (1)
    {
        fgets(buf,N,stdin);
        buf[strlen(buf)-1] = '\0';//Convert \ n in buf string to \ 0
        if(sendto(sockfd,buf,N,0,(struct sockaddr *)&serveraddr,addrlen) == -1)
        {
            perror("fail tp sendto");
            exit(1);
        }
    }
    
    //Step 4: close the socket file descriptor
    close(sockfd);

    return 0;
}

Topics: network Network Protocol udp