linux系统编程-SOCKET通信基础编程(2)-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 CLIENT_PORT 6789
#define BUFLEN 256

int main()
{
	int ret = 0;
	int ret1= 0;
    int fd=0;
	char buf[BUFLEN] = {0};
	
	struct sockaddr_in server_addr;
	socklen_t socklen = sizeof(server_addr);
	bzero(&server_addr, sizeof(server_addr));
	
	//1,创建socket
	int cli_sock = socket(AF_INET, SOCK_DGRAM, 0);
	if(cli_sock < 0)
	{
		perror("socket");
		return -1;
	}
	
	//可选,
	struct sockaddr_in cli_addr;
	bzero(&cli_addr, sizeof(cli_addr));
	cli_addr.sin_family = AF_INET;
	cli_addr.sin_port = htons(CLIENT_PORT);
	cli_addr.sin_addr.s_addr = INADDR_ANY;
	
	if(bind(cli_sock, (struct sockaddr *)&cli_addr, sizeof(cli_addr)) < 0)
	{
		perror("bind");
		goto sock_err;
	}
	
	//2,填写服务器地址信息
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(SERVER_PORT);
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	
	strcpy(buf, "I am a client");
	if((ret = sendto(cli_sock, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, socklen)) < 0)
	{
		perror("sendto");
		goto sock_err;
	}
	
	while(1){
		//发送数据
	   bzero(buf, sizeof(buf));
	   scanf("%s",buf);
		if((ret = sendto(cli_sock, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, socklen)) < 0)
		{
			perror("sendto");
			goto sock_err;
		}
		//接收数据
	   bzero(buf, sizeof(buf));
	   ret = recvfrom(cli_sock, buf, BUFLEN, 0, (struct sockaddr *)&server_addr, &socklen);
	   if(ret < 0)
	   {
		  perror("recvfrom");
		  goto sock_err;
	   }

	   printf("recvfrom:%s\n", buf);
	}
sock_err:
	//5,关闭socket
    close(fd);
	close(cli_sock);
	return ret;
}

 

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