基於UDP協議的網絡編程

下圖是典型的UDP客戶端/服務器通訊過程[下圖出自《Unix網絡編程》]

以下是簡單的UDP服務器和客戶端程序,服務端接收來自客戶端的字符,轉成大寫後返送給客戶端。

備註:程序在ubuntu10.04經過編譯驗證,可直接使用。

服務端程序:

/* server.c */
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <ctype.h>
#include <error.h>

#define MAXLINE 80
#define SERV_PORT 8000

void perr_exit(const char *s)
{
	perror(s);
	exit(1);
}

int main(void)
{
	struct sockaddr_in server_addr; 
	struct sockaddr_in client_addr;	
	int sockfd;
	int sin_size, read_bytes, send_bytes;
	char buf[MAXLINE];
	char str[INET_ADDRSTRLEN];
	int i, n;

	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perr_exit("create socket error");
	}

	bzero(&server_addr, sizeof(struct sockaddr_in));
	bzero(&server_addr, sizeof(struct sockaddr_in));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	server_addr.sin_port = htons(SERV_PORT);
    
	if(bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)))
	{
		perr_exit("bind error");
	}

	printf("Accepting connections ...\n");
	sin_size = sizeof(struct sockaddr);
	while (1)
	{
		memset(buf, '\0', MAXLINE);	
		read_bytes = recvfrom(sockfd, buf, MAXLINE, 0, (struct sockaddr *)&client_addr, &sin_size);
		if (n == -1)
		{
			perr_exit("recvfrom error");
		}
		printf("received from %s at PORT %d\n",
		       (char *)inet_ntop(AF_INET, &client_addr.sin_addr, str, sizeof(str)),
		       (int)ntohs(client_addr.sin_port));
    
		for (i = 0; i < read_bytes; i++)
		{
			buf[i] = toupper(buf[i]);
		}
		send_bytes = sendto(sockfd, buf, read_bytes, 0, (struct sockaddr *)&client_addr, sin_size);
		if (send_bytes == -1)
		{
			perr_exit("sendto error");
		}
	}
}

客戶端程序:
/* client.c */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <errno.h>

#define MAXLINE 80
#define SERV_PORT 8000

void perr_exit(const char *s)
{
	perror(s);
	exit(1);
}

int main(int argc, char *argv[])
{
	struct sockaddr_in server_addr;
	int sockfd, n;
	int sin_size, read_bytes, send_bytes;
	char buf[MAXLINE];
	char str[INET_ADDRSTRLEN];
	socklen_t servaddr_len;
    
	if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
	{
		perr_exit("create sockte error");
	}

	bzero(&server_addr, sizeof(struct sockaddr_in));
	server_addr.sin_family = AF_INET;
	inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr);
	server_addr.sin_port = htons(SERV_PORT);
    
	while (fgets(buf, MAXLINE, stdin) != NULL)
	{
		send_bytes = sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
		if (send_bytes == -1)
		{
			perr_exit("sendto error");
		}

		read_bytes = recvfrom(sockfd, buf, MAXLINE, 0, NULL, 0);
		if (n == -1)
		{
			perr_exit("recvfrom error");
		}
	  	printf("recvfrom:%s\n", buf);
	}

	close(sockfd);
	return 0;
}

發佈了42 篇原創文章 · 獲贊 15 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章