C语言实现udp
udp_server.c
#include <stdio.h>
#include <strings.h>
#include "arpa/inet.h"
void udp_server() {
printf("%s\n","in udp server");
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0) {
perror("");
}
//绑定
//
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9090);
//绑定自己本机的ip
// inet_pton(AF_INET,"192.168.127.129",&addr.sin_addr.s_addr);
addr.sin_addr.s_addr = INADDR_ANY; //通配地址
int ret=bind(sock_fd,(struct sockaddr*)&addr,sizeof(addr));
if(ret<0){
perror("");
}
struct sockaddr_in cli_addr;
socklen_t len = sizeof(cli_addr);
while (1){
char buf[128]="";
int n = recvfrom(sock_fd,buf, sizeof(buf),0,(struct sockaddr*)&cli_addr, &len);
printf("%s\n",buf);
sendto(sock_fd,buf,n,0,(struct sockaddr*)&cli_addr, sizeof(cli_addr));
}
}
int main() {
udp_server();
return 0;
}
udp_client.c
#include <stdio.h>
#include <strings.h>
#include "arpa/inet.h"
void client(){
//ipv4的套接字结构体
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9090);//转大端,这是目标机器的port
inet_pton(AF_INET, "10.13.168.224", &server_addr.sin_addr.s_addr);
// 创建套接字
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0) {
perror("");
}
while (1) {
char buf[128] = "";
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = 0;
sendto(sock_fd, buf, strlen(buf), 0, (struct sockaddr *) &server_addr, sizeof(server_addr));
char read_buf[128] = "";
recvfrom(sock_fd, read_buf, sizeof(read_buf), 0, NULL, NULL);
printf("%s\n", read_buf);
}
}
int main() {
client();
return 0;
}