udp_client
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
int fd;
char buf[1024];
struct sockaddr_in addr;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if ( fd < 0 )
{
printf("socket err\n");
}
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("192.168.2.11");
while ( 1 )
{
memset(buf, 0x00, sizeof(buf));
sendto(fd, "hello", strlen("hello"), 0, (struct sockaddr*)&addr, sizeof(addr));
recvfrom(fd, buf, sizeof(buf), 0, NULL, 0);
printf("buf = %s\n", buf);
}
}
udp_service
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
int main()
{
int fd, cfd, ret;
char buf[1024];
struct sockaddr_in addr, client;
fd = socket(AF_INET, SOCK_DGRAM, 0);
if ( fd < 0 )
{
printf("socket err\n");
}
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("192.168.2.11");
ret = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
if ( ret < 0 )
{
printf("bind err\n");
}
socklen_t len = sizeof(addr);
while ( 1 )
{
memset(buf, 0x00, sizeof(buf));
cfd = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&client, &len);
printf("buf = %s\n", buf);
ret = sendto(fd, "nihao", strlen("nihao"), 0, (struct sockaddr*)&client, len);
if (ret < 0)
{
printf("send err\n");
}
}
}
udp用的是recvfrom和sendto函數,第一次參數是一個文件描述符,後面兩個是目的地址/接口,tcp用的是recv和send往socket綁定的地方收發
|