网络编程 单纯UDP通信
1,UDP发送端
2,UDP接收端
UDP发送端:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char* argv[]){
int sock;
sockaddr_in addr;
int n;
if(argc != 2){
return 1;
}
sock = socket(AF_INET, SOCK_DGRAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
inet_pton(AF_INET, argv[1], &addr.sin_addr.s_addr);
n = sendto(sock, "aaaaa", 5, 0, (sockaddr*)&addr, sizeof(addr));
close(sock);
return 0;
}
发送端的执行方式:
./a.out 127.0.0.1
UDP接收端
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(){
int sock;
sockaddr_in addr;
sockaddr_in senderinfo;
socklen_t addrlen;
char buf[2048];
int n;
sock = socket(AF_INET, SOCK_DGRAM, 0);
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = INADDR_ANY;
bind(sock, (sockaddr*)&addr, sizeof(addr));
addrlen = sizeof(senderinfo);
n = recvfrom(sock, buf, sizeof(buf) - 1, 0,
(sockaddr*)&senderinfo, &addrlen);
write(fileno(stdout), buf, n);
close(sock);
return 0;
}