服务器:
1:
2: #include <stdio.h>
3: #include <sys/socket.h>
4: #include <netinet/in.h>
5: #include <arpa/inet.h>
6: #include <string.h>
7: #include <strings.h>
8: #include <stdlib.h>
9:
10:
11: #define N 256
12:
13: typedef struct sockaddr SA;
14:
15: int main(int argc, char* argv[])
16: {
17: int sockfd;
18: struct sockaddr_in my_addr, peer_addr;
19: socklen_t peerlen = sizeof(peer_addr);
20: char buffer[N];
21:
22: if((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
23: {
24: perror("fail to socket");
25: exit(-1);
26: }
27:
28: my_addr.sin_family = PF_INET;
29: my_addr.sin_port = htons(atoi(argv[2]));
30: my_addr.sin_addr.s_addr = inet_addr(argv[1]);
31:
32: if(bind(sockfd, (SA *)&my_addr, sizeof(my_addr)) < 0)
33: {
34: perror("fail to bind");
35: exit(-1);
36: }
37:
38: while(1)
39: {
40:
41: recvfrom(sockfd, buffer, N, 0,(SA*)&peer_addr, &peerlen);
42: printf("client: [%s : %d], %s",inet_ntoa(peer_addr.sin_addr),ntohs(peer_addr.sin_port),buffer);
43: sendto(sockfd, buffer, N, 0, (SA *)&peer_addr, sizeof(peer_addr));
44: bzero(buffer, N);
45: }
46:
47:
48: return 0;
49: }
客户端:
1: #include <stdio.h>
2: #include <sys/socket.h>
3: #include <netinet/in.h>
4: #include <arpa/inet.h>
5: #include <string.h>
6: #include <strings.h>
7: #include <stdlib.h>
8: #include <unistd.h>
9:
10:
11: #define N 256
12:
13: typedef struct sockaddr SA;
14:
15: int main(void)
16: {
17: int sockfd;
18: struct sockaddr_in my_addr;
19: char buffer[N];
20:
21: if((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
22: {
23: perror("fail to socket");
24: exit(-1);
25: }
26:
27:
28:
29: while(1)
30: {
31:
32: bzero(buffer, N);
33: printf("exit? Y/N");
34: fgets(buffer, N, stdin);
35: if(strncmp(buffer, "Y", 1) == 0)
36: {
37: break;
38: }
39: else
40: {
41: bzero(&my_addr,sizeof(my_addr));
42: my_addr.sin_family = PF_INET;
43:
44: printf("please input server's ip > ");
45: fgets(buffer, N, stdin);
46: buffer[strlen(buffer) -1] = '\0';
47: my_addr.sin_addr.s_addr = inet_addr(buffer);
48:
49: printf("please input server's port > ");
50: fgets(buffer, N, stdin);
51: buffer[strlen(buffer) -1] = '\0';
52: my_addr.sin_port = htons(atoi(buffer));
53:
54: connect(sockfd, (SA *)&my_addr, sizeof(my_addr));
55: while(1)
56: {
57: fgets(buffer, N, stdin);
58: if(strncmp(buffer, "quit", 4) == 0)
59: {
60: break;
61: }
62:
63: send(sockfd, buffer, N, 0);
64: bzero(buffer, N);
65: recv(sockfd, buffer, N, 0);
66: printf("receive from the server > %s",buffer);
67: }
68: }
69: }
70:
71: close(sockfd);
72: return 0;
73: }
运行:
运行了两个服务器:
客户端:
这样,通过在UDP中使用connect(),省去了每次都输入服务器地址的操作,而且一个在这种情况下,一个套接字在不关闭的情况下可以实现多次调用connect()。