Linux網絡編程UDP:服務器與客戶端之間的相互發(fā)送/接收(一)
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #define MAX_SEN 200 #define MAX_REC 200 #define SERADDR "192.168.1.11" #define SERPORT 8000 int main(void) { int c_fd = -1, num = 0; char cli_senbuf[MAX_SEN] = "abcdefg"; char cli_recbuf[MAX_REC]; struct sockaddr_in sin = {0}; struct sockaddr_in cin = {0}; socklen_t addr_len; c_fd = socket(AF_INET, SOCK_DGRAM, 0); if ( -1 == c_fd) { perror("socket"); return -1; } printf("c_fd = %d.\n", c_fd); sin.sin_family = AF_INET; sin.sin_port = htons(SERPORT); inet_pton(AF_INET, SERADDR, &sin.sin_addr); num = sendto(c_fd, cli_senbuf, strlen(cli_senbuf), 0, (const struct sockaddr *)&sin, sizeof(sin)); printf("客戶端成功發(fā)送了%d個字符\n", num); printf("客戶端發(fā)送的內容是:%s\n", cli_senbuf); num = recvfrom(c_fd, cli_recbuf, MAX_REC, 0, (struct sockaddr *)&cin, &addr_len); printf("客戶端成功接收了%d個字節(jié)\n", num); printf("客戶端接收的內容是:%s\n", cli_recbuf); return 0; }
server.c
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <string.h> #define MAX_SEN 200 #define MAX_REC 200 #define SERPORT 8000 int main(void) { int s_fd = -1, ret = -1; char ser_senbuf[MAX_SEN] = "hello"; char cli_recbuf[MAX_REC]; struct sockaddr_in ser_sin = {0}; struct sockaddr_in ser_cin = {0}; socklen_t addr_len; char ipbuf[INET_ADDRSTRLEN]; s_fd = socket(AF_INET,SOCK_DGRAM,0); if (s_fd == -1 ) { perror("socket"); return -1; } printf("s_fd = %d.\n", s_fd); bzero(&ser_sin,sizeof(ser_sin)); ser_sin.sin_family = AF_INET; ser_sin.sin_addr.s_addr = INADDR_ANY; ser_sin.sin_port = htons(SERPORT); ret = bind(s_fd, (const struct sockaddr *)&ser_sin, sizeof(ser_sin)); if (ret < 0) { perror("bind"); return -1; } printf("bind success.\n"); addr_len = sizeof(ser_cin); ret = recvfrom(s_fd, cli_recbuf, MAX_REC, 0, (struct sockaddr *)&ser_cin, &addr_len); printf("服務器成功接收了%d個字節(jié)\n", ret); printf("服務器接收的內容是:%s\n", cli_recbuf); inet_ntop(AF_INET, &ser_cin.sin_addr, ipbuf,sizeof(ipbuf)); printf("ip地址是:%s\n", ipbuf); ret = sendto(s_fd, ser_senbuf, strlen(ser_senbuf), 0, (const struct sockaddr *)&ser_cin, addr_len); printf("服務器成功發(fā)送了%d個字符\n", ret); printf("服務器發(fā)送的內容是:%s\n", ser_senbuf); return 0; }
*博客內容為網友個人發(fā)布,僅代表博主個人觀點,如有侵權請聯系工作人員刪除。