linux系统编程-SOCKET通信基础编程(1)-UDP编程服务端程序

 

linux系统编程-SOCKET通信基础编程(0)-UDP编程

linux系统编程-SOCKET通信基础编程(1)-UDP编程服务端程序

linux系统编程-SOCKET通信基础编程(2)-UDP编程客户端程序

 

UDP编程服务端程序

#include 
#include           /* See NOTES */
#include 
#include 
#include 
#include 
#include 
#include 

#define SERVER_PORT 8888
#define BUFLEN 256

int setup_socket()
{
	//1,创建socket
	int sock_server = socket(AF_INET, SOCK_DGRAM, 0);
	if(sock_server < 0)
	{
		perror("socket");
		return -1;
	}
	
	//2,填充地址信息
	struct sockaddr_in server_addr;
	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(SERVER_PORT);
	server_addr.sin_addr.s_addr = INADDR_ANY;
	
	//设置可以复用地址
	int on = 1;
	if(setsockopt(sock_server, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) == -1){
		perror("setsockopt");
		return -1;
	}
	
	//3,bind
	if(bind(sock_server, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
	{
		return -1;
	}
	
	return sock_server;	
}

int main()
{
	char buf[BUFLEN] = {0};
	int ret = 0, server_sock;
    int fd =0;
	int ret1=0;

	struct sockaddr_in client_addr;
	bzero(&client_addr, sizeof(client_addr));
	socklen_t len = sizeof(client_addr);

	server_sock = setup_socket();
	if(server_sock < 0)
	{
		return -1;
	}
	
	while(1)
	{	
		//4, 收数据
		bzero(buf, sizeof(buf));
		if((ret = recvfrom(server_sock, buf, BUFLEN-1, 0, (struct sockaddr*)&client_addr, &len)) < 0)
		{
			perror("recvfrom");
			return -1;
		}
	
		printf("client ip:%s, port: %d\n", (char *)inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
		printf("recvfrom : %s\n", buf);	

        //发送数据给客户端		
		bzero(buf, sizeof(buf));
        scanf("%s",buf);
		ret = sendto(server_sock, buf,strlen(buf),  0, (const struct sockaddr * )&client_addr, len);
		if(ret < 0)
		{
			perror("recvfrom");
			return -1;
		}	       
	}
	close(fd);
	return ret;
}

 

你可能感兴趣的:(linux系统编程)