Liby's Blog

 汝鬼耶,抑人耶?

UDP服务器端与客户端

without comments

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
 
#define PORT_SERVER 9898
 
int main()
{
	int socket_fd;
	int nrecv;
	int size;
	struct sockaddr_in ad_s;
	char buffer[1024];
 
	if((socket_fd=socket(AF_INET,SOCK_DGRAM,0))==-1)
	{
		fprintf(stderr,"socket error\n");
		exit(1);
	}
	bzero(&ad_s,sizeof(ad_s));
	ad_s.sin_family=AF_INET;
	ad_s.sin_addr.s_addr=htonl(INADDR_ANY);
	ad_s.sin_port=htons(PORT_SERVER);
 
	if(bind(socket_fd,(struct sockaddr *)&ad_s,sizeof(ad_s)))
	{
		fprintf(stderr,"bind error\n");
		exit(1);
	}
 
	while(1)
	{
		bzero(buffer,1024);
		size=sizeof(struct sockaddr);
		nrecv=recvfrom(socket_fd,buffer,1024,0,(struct sockaddr *)&ad_s,&size);
		buffer[nrecv]='\0';
		printf("server receive %s\n",buffer);
	}
	close(socket_fd);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
 
#define PORT_CLIENT 9898
 
int main(int argv,char *argc[])
{
	struct hostent *host;
	if(argv<2)
	{
		perror("parameter error\n");
		exit(1);
	}
	if((host=gethostbyname(argc[1]))==NULL)
	{
		fprintf(stderr,"gethostname error\n");
		exit(1);
	}
 
	int socket_fd;
	struct sockaddr_in ad_s;
	char buffer[1024];
 
	if((socket_fd=socket(AF_INET,SOCK_DGRAM,0))==-1)
	{
		fprintf(stderr,"socket error\n");
		exit(1);
	}
	bzero(&ad_s,sizeof(ad_s));
	ad_s.sin_family=AF_INET;
	ad_s.sin_port=htons(PORT_CLIENT);
	ad_s.sin_addr=*((struct in_addr*)host->h_addr);
 
	while(1)
	{
		printf("input something:\n");
		fgets(buffer,1024,stdin);
 
		if(sendto(socket_fd,buffer,strlen(buffer),0,(struct sockaddr *)&ad_s,sizeof(ad_s))==-1)
		{
			fprintf(stderr,"sendto error\n");
			exit(1);
		}
		bzero(buffer,1024);
	}
	close(socket_fd);
 
}

Written by liby

3 10th, 2012 at 19:48

Posted in 技事巧事

Tagged with , ,

Leave a Reply