Linux-UDP socket程式設計
阿新 • • 發佈:2018-11-03
伺服器
1、建立連線
socket(),分配檔案描述符,即監聽套接字
bind(),將套接字與本地IP地址和埠繫結
2、資料收發
recvfrom()阻塞等待客戶端傳送資料
sendto()將處理結果傳送給客戶端
3、關閉連線
close()關閉套接字
客戶端
1、建立連線
socket(),分配檔案描述符
2、資料收發
sendto()傳送資訊給服務端
recvfrom()阻塞等待服務端返回送資料
3、關閉連線
close()關閉套接字
UDP通訊
示例程式碼
標頭檔案:header.h
#ifndef _STD_ #define _STD_ // 標頭檔案 // #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <dirent.h> #include <sys/types.h> #include <grp.h> #include <string.h> #include <time.h> #include <string.h> #include <errno.h> //tcp// #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netinet/ip.h> #include <arpa/inet.h> //錯誤提示// #define err_exit(function) \ do { \ fprintf(stderr, "in %s at %s %d:\n%s : %s\n", __FUNCTION__, __FILE__, __LINE__ - 1, function, strerror(errno)); \ exit(EXIT_FAILURE); \ } while(0) #endif
服務端:test_udp_server.c
#include "header.h" int main(int argc, char *argv[]) { int sockfd = -1; struct sockaddr_in server,client; char buf[BUFSIZ]; //初始化套接字地址結構體 memset(&server, 0, sizeof(server)); server.sin_family = AF_INET;//IPv4 server.sin_port = htons(888);//設定埠號 server.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY接收任意IP的請求 //建立套接字 if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, 0))) err_exit("socket"); //繫結套接字和本地IP地址和埠 if(0 > bind(sockfd, (struct sockaddr *)&server, sizeof(server))) err_exit("bind"); //初始化客戶端套接字地址 bzero(&client, sizeof(client)); socklen_t len = sizeof(client); while(1) { //接受客戶端發來的資訊 memset(buf, 0, sizeof(buf)); recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &len); printf("client's ip is: %s, port is: %d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); printf("client:%s\n", buf); //向客戶端傳送資訊 memset(buf, 0, sizeof(buf)); fgets(buf, sizeof(buf), stdin); sendto(sockfd, buf, strlen(buf) + 1, MSG_NOSIGNAL, (struct sockaddr *)&client, sizeof(client)); } close(sockfd); exit(0); }
客戶端:test_udp_client.c
#include "header.h"
int main(int argc, char *argv[])
{
int sockfd = -1;
struct sockaddr_in server;
char buf[BUFSIZ];
//初始化伺服器套接字地址
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;//IPv4
server.sin_port = htons(888);//伺服器埠
server.sin_addr.s_addr = inet_addr("192.168.1.50");//指定伺服器IP地址
//server.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY接收任意IP的請求
socklen_t len = sizeof(server);
//建立套接字
if (0 > (sockfd = socket(AF_INET, SOCK_DGRAM, 0)))
err_exit("socket");
while(1)
{
//向伺服器傳送資訊
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
sendto(sockfd, buf, strlen(buf) + 1, MSG_NOSIGNAL, (struct sockaddr *)&server, sizeof(server));
//接收伺服器資訊
recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&server, &len);
printf("server's ip is: %s, port: is %d\n", inet_ntoa(server.sin_addr), ntohs(server.sin_port));
printf("server:%s\n", buf);
}
close(sockfd);
exit(0);
}