📄 client.c
字号:
/* Simple UDP client - sends a 32 bit integer to the server and quits. This is just an example showing what can happen when you don't pay attention to network byte order!*/ #include <stdio.h> /* standard C i/o facilities */#include <stdlib.h> /* needed for atoi() */#include <unistd.h> /* defines STDIN_FILENO, system calls,etc */#include <sys/types.h> /* system data type definitions */#include <sys/socket.h> /* socket specific definitions */#include <netinet/in.h> /* INET constants and stuff */#include <arpa/inet.h> /* IP address conversion stuff */#include <netdb.h> /* gethostbyname *//* client program: The following must passed in on the command line: hostname of the server (argv[1]) port number of the server (argv[2]) the number we want to send (argv[3])*/int main( int argc, char **argv ) { int sk; struct sockaddr_in server; struct hostent *hp; int n_sent; int num; /* Make sure we have the right number of command line args */ if (argc!=4) { printf("Usage: %s <server name> <port number> <number>\n",argv[0]); exit(0); } /* create a socket IP protocol family (PF_INET) UDP (SOCK_DGRAM) */ if ((sk = socket( PF_INET, SOCK_DGRAM, 0 )) < 0) { printf("Problem creating socket\n"); exit(1); } /* Using UDP we don't need to call bind unless we care what our port number is - most clients don't care */ /* now create a sockaddr that will be used to contact the server fill in an address structure that will be used to specify the address of the server we want to connect to address family is IP (AF_INET) server IP address is found by calling gethostbyname with the name of the server (entered on the command line) server port number is argv[2] (entered on the command line) */ server.sin_family = AF_INET; if ((hp = gethostbyname(argv[1]))==0) { printf("Invalid or unknown host\n"); exit(1); } /* copy the IP address into the sockaddr It is already in network byte order */ memcpy( &server.sin_addr.s_addr, hp->h_addr, hp->h_length); /* establish the server port number - we must use network byte order! */ server.sin_port = htons(atoi(argv[2])); /* now get the number we want to send */ num = atoi(argv[3]); // num = htonl(num); /* send it to the server */ n_sent = sendto(sk,&num,sizeof(num),0, (struct sockaddr*) &server,sizeof(server)); if (n_sent<0) { perror("Problem sending data"); exit(1); } printf("Sendto sent %d bytes\n",n_sent); printf("The number sent was %d\n",num); return(0);}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -