The UDPClient program is a common program. In many language tutorials, there are application explanations for anger. Now we will explain how to use the C language to implement UDPClient. Now let's take a closer look at the specific steps for writing the UDPClient program.
1) initialize the variables in the sockaddr_in structure and assign values. Here, "8888" is used as the port to connect to the service program, read the IP address from the command line parameters, and determine whether the IP address meets the requirements.
2) Use socket) to create a UDP socket. The second parameter is SOCK_DGRAM.
3) connect to the service program. Unlike TCP, UDP connect does not shake hands with the service program three times. As mentioned above, UDP is non-connected and can actually be connected. Using the connected UDP, the kernel can directly return the error message to the user program, so as to avoid calling recvfrom because the data is not received. It seems that the customer program does not respond.
4) send data to the service program. Because UDP is connected, write is used to replace sendto ). The data here reads the user input directly from the standard input.
5) receive the data sent back by the service program, and also use read) to replace recvfrom ).
6) process the received data, which is directly output to the standard output.
Udpclient. c program content:
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #include
- #define MAXLINE 80
- #define SERV_PORT 8888
- void do_cliFILE *fp, int sockfd, struct sockaddr *pservaddr, socklen_t servlen)
- {
- int n;
- char sendline[MAXLINE], recvline[MAXLINE + 1];
- /* connect to server */
- ifconnectsockfd, struct sockaddr *)pservaddr, servlen) == -1)
- {
- perror"connect error");
- exit1);
- }
- whilefgetssendline, MAXLINE, fp) != NULL)
- {
- /* read a line and send to server */
- writesockfd, sendline, strlensendline));
- /* receive data from server */
- n = readsockfd, recvline, MAXLINE);
- ifn == -1)
- {
- perror"read error");
- exit1);
- }
- recvline[n] = 0; /* terminate string */
- fputsrecvline, stdout);
- }
- }
- int mainint argc, char **argv)
- {
- int sockfd;
- struct sockaddr_in srvaddr;
- /* check args */
- ifargc != 2)
- {
- printf"usage: udpclient \n");
- exit1);
- }
- /* init servaddr */
- bzero&servaddr, sizeofservaddr));
- servaddr.sin_family = AF_INET;
- servaddr.sin_port = htonsSERV_PORT);
- ifinet_ptonAF_INET, argv[1], &servaddr.sin_addr) <= 0)
- {
- printf"[%s] is not a valid IPaddress\n", argv[1]);
- exit1);
- }
- sockfd = socketAF_INET, SOCK_DGRAM, 0);
- do_clistdin, sockfd, struct sockaddr *)&servaddr, sizeofservaddr));
- return 0;
- }