写来一个UDP发送和接受数据包的程序.
客户端代码:
client_main.c:
/*
* @file client_main.c
* @brief client of the UDP.
* @author xiaou
*/
#include // for sockaddr_in
#include // for socket
#include // for socket
#include // for close()
#include
#include
#include
int main(int argc, char *argv[])
{
if(argc < 2)
{
printf("One argument at least!\n");
return -1;
}
int res = 0;
int sock_fd = socket(PF_INET, SOCK_DGRAM, 0);
if(sock_fd < 0)
{
printf("error: Create Socket Failed!");
return -1;
}
struct sockaddr_in sock_addr;
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(4321);
sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(sock_addr.sin_zero, 0x00, 8);
try
{
const char * tos = argv[1];
int toslen = strlen(tos) + 1;
struct sockaddr_in to = sock_addr;
uint32_t tolen = sizeof(struct sockaddr);
printf("\nSending for data...\n");
if((toslen = sendto(sock_fd, tos, toslen, 0, (struct sockaddr *)&to, tolen)) == -1)
{
printf("error: Sending Failed!");
res = -1;
throw res;
}
else
{
char s[256];
strncpy(s, tos, toslen);
printf("Sended data:\n[%s]\n\n", s);
}
}
catch(...)
{
printf("error catched~");
}
close(sock_fd);
return res;
}
服务端代码:
server_main.c:
/*
* @file server_main.c
* @brief server of the UDP.
* @author xiaou
*/
#include // for sockaddr_in
#include // for socket
#include // for socket
#include // for close()
#include
#include
#include
int main(int argc, char *argv[])
{
int res = 0;
int sock_fd = socket(PF_INET, SOCK_DGRAM, 0);
if(sock_fd < 0)
{
printf("error: Create Socket Failed!");
return -1;
}
struct sockaddr_in sock_addr;
sock_addr.sin_family = AF_INET;
sock_addr.sin_port = htons(4321);
sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);
memset(sock_addr.sin_zero, 0x00, 8);
try
{
if(bind(sock_fd, (struct sockaddr *)&sock_addr, sizeof(struct sockaddr)) != 0)
{
printf("error: Bind Socket Failed!");
res = -1;
throw res;
}
char recvs[256];
int recvslen;
struct sockaddr_in from;
uint32_t fromlen;
while(1)
{
printf("\nWaiting for data...\n");
fromlen = sizeof(struct sockaddr);
if((recvslen = recvfrom(sock_fd, recvs, 256, 0, (struct sockaddr *)&from , &fromlen)) == -1)
{
printf("error: Receiving Failed!");
res = -1;
throw res;
}
else
{
if(recvslen < 256)
*(recvs+recvslen) = '\0';
else
*(recvs+255) = '\0';
printf("Received data:\n[%s]\n",recvs);
}
}
}
catch(...)
{
printf("error catched~");
}
close(sock_fd);
return res;
}
Makefile代码:
Makefile:
CC=g++
CFLAGS=-Wall
OutPath4UDPClient=$(HOME)/bin/test4UDPClient
OutPath4UDPServer=$(HOME)/bin/test4UDPServer
all:
$(CC) $(CFLAGS) -o $(OutPath4UDPClient) client_main.c
$(CC) $(CFLAGS) -o $(OutPath4UDPServer) server_main.c
clean:
rm -rf $(OutPath4UDPClient)
rm -rf $(OutPath4UDPServer)
发表评论
要发表评论,您必须先登录。