Address structuresockaddr_in
These include:IP address , port number , protocol family
Recommended Use sockaddr_in
, not recommendedsockaddr
sockaddr_in
is equivalent, but sockaddr_in
the field is clearer sockaddr
/**/struct sockaddr_in { __uint8_t Sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; Char sin_zero[8];};
sockaddr_inField description
// address family, typically using af_inet to represent the TCP/CP protocol family (Af_inet6 for IPV6) sockaddr_in.sin_family // port number, must be converted to network byte order using htons and Ntohs Sockaddr_in.sin_port // used to store IP addresses, which must be a network byte order sockaddr_in.sin_addr // in order to keep SOCKADDR and sockaddr_in two data structures the same size as the reserved empty bytes Sockaddr_in.sin_zero
sockaddr_inField initialization
structsockaddr_in Servaddr;bzero (&SERVADDR,sizeof(SERVADDR)); servaddr.sin_family=Af_inet;servaddr.sin_port= Htons (8090);//converts a string to a IPV4 address of a 32-bit binary network byte order if the string is validSERVADDR.SIN_ADDR.S_ADDR = inet_addr ("127.0.0.1");//Detect conversion IP errorif(Servaddr.sin_addr.s_addr = =Inaddr_none) {Perror ("IP"); Exit (-1);}
The function to use
// Convert network byte order to host byte order __uint16_t Ntohs (__uint16_t); // Convert host byte order to network byte order __uint16_t htons (__uint16_t); __uint32_t Ntohl (__uint32_t); __uint32_t htonl (__uint32_t) ; // if the string is valid, convert the string to the IPV4 address of the 32-bit binary network byte order, otherwise inaddr_none // its inverse function inet_ntoain_addr_t inet_addr (constChar* strptr);
can support IPV6 IP address translation mode
// Inet_pton can handle IPv4 even IPv6 (need to change the code now) if " 127.0.0.1 " 0 ) { perror ("pton"); Exit (-1);}
Sockets
Creates a socket that returns a socket descriptor
int socket (intint int protocol);
Socket Descriptor (socket file descriptor)
A socket descriptor is a value of an integer type that has a socket descriptor table in the process space of each process that holds the corresponding relationship between the socket descriptor and the socket data structure.
Therefore, the corresponding socket data structure can be found based on the socket descriptor.
Each process has a socket descriptor in its own process space, but the socket data structure is in the kernel buffer of the operating system
Receive Send function
ssize_t recv (intvoidint flags); ssize_t Send (intconst voidint flags); ssize_t write (int fd,constvoid * buf,size _t count); ssize_t read (int fd,void * buf, size_t count);
Client main functions
int Connect (int sockfd,struct sockaddr * serv_addr,int addrlen);
Server-side main functions
int int Const struct sockaddr * my_addr, socklen_t addrlen); int Listen (intint. backlog); int Accept (intstructint * Addrlen);
Client code
#include <iostream>#include<sys/types.h>#include<netinet/inch.h>#include<sys/socket.h>#include<sys/wait.h>#include<arpa/inet.h>#include<unistd.h>Const intMax_line = +;Const ushortServ_port =7890;Const Char* Serv_ip ="127.0.0.1";intMainintargcConst Char*argv[]) { intsocketfd; structsockaddr_in servaddr; memset (&SERVADDR,0,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port=htons (Serv_port); //converts a string to a IPV4 address of a 32-bit binary network byte order if the string is valid//servaddr.sin_addr.s_addr = inet_addr (SERV_IP);//if (servaddr.sin_addr.s_addr = = Inaddr_none) {//perror ("IP");//exit ( -1);// } //Support IPV6 's new conversion method, recommended if(Inet_pton (Af_inet,"127.0.0.1", &servaddr.sin_addr) <=0) {perror ("Pton"); Exit (-1); } //Create a socket if(SOCKETFD = socket (af_inet, Sock_stream,0)) <0) {perror ("Socket"); Exit (-1); } //Connect to host if(Connect (SOCKETFD, (sockaddr*) &servaddr,sizeof(SERVADDR)) <0) {perror ("Connect"); Exit (-1); } //Receive Data CharRecvline[max_line+1]; LongBytelen =0; while((Bytelen = Read (SOCKETFD, Recvline, max_line)) >0) {Recvline[bytelen]=0; printf ("recv-%s\n", Recvline); } close (SOCKETFD); return 0;}
Server code
#include <iostream>#include<sys/types.h>#include<netinet/inch.h>#include<sys/socket.h>#include<sys/wait.h>#include<arpa/inet.h>#include<unistd.h>Const ushortServ_port =7890;intMainintargcConst Char*argv[]) { structsockaddr_in serveraddr; memset (&SERVERADDR,0,sizeof(SERVERADDR)); Serveraddr.sin_family=af_inet; Serveraddr.sin_port=htons (Serv_port); //the system automatically obtains the native IPSERVERADDR.SIN_ADDR.S_ADDR =htonl (Inaddr_any); //Create a socket intSERVERFD = socket (Af_inet,sock_stream,0); if(Serverfd <0) {perror ("Socket"); Exit (-1); } //Binding Port intBind_ret = Bind (SERVERFD, (structSOCKADDR *) &serveraddr,sizeof(SERVERADDR)); if(Bind_ret <0) {perror ("Bind"); Exit (-1); } //Start listening .//#2: Backlog: Maximum length to wait for a connection queue if(Listen (SERVERFD,Ten) <0) {perror ("Listen"); Exit (-1); } printf ("----------Listening (127.0.0.1:%d)----------\ n", Serv_port); //start polling for listener requests BOOLToggle =true; while(toggle) {//Client Information Structure intclientfd; structsockaddr_in clientaddr; memset (&SERVERADDR,0,sizeof(SERVERADDR)); socklen_t Len=sizeof(CLIENTADDR); //receive requests, establish connections if(Clientfd = Accept (SERVERFD, (structSOCKADDR *) &clientaddr, &len) <0) {perror ("Accept"); Exit (-1); } //send a message to the client Const Char*message ="Hello World"; Write (CLIENTFD, message, strlen (message)+1); //Convert to dot decimal IP Const Char*CLIENT_IP =Inet_ntoa (CLIENTADDR.SIN_ADDR); Const ushortClient_port =Ntohs (Clientaddr.sin_port); printf ("Client (%s:%u) # send-and%s\n", CLIENT_IP, Client_port, message); //Close the connection to the clientClose (CLIENTFD); } //Turn off service snoopingClose (SERVERFD); return 0;}
Socket Foundation Programming