ÒÔÏÂÄÚÈÝΪUDPÍøÂçͨÐÅÖзþÎñÆ÷µÄ¼òµ¥Ê¾Àý´úÂ룺
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
int main(int argc, char* argv[])
{
int err, sfd;
//1)°ÑIPµØÖ·£¬IPÐÒé×å·â×°³ÉÌ×½Ó×Ösocket
sfd = socket(AF_INET, SOCK_DGRAM, 0);
if(sfd < 0)
{
printf("Failed to create socket\n");
return -1;
}
printf("The socket was created successfully\n");
//2)±àд·þÎñÆ÷ÐÅÏ¢½á¹¹Ìå
struct sockaddr_in saddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;//µØÖ·ÐÒé×å
saddr.sin_port = htons(atoi(argv[2]));//¶Ë¿ÚºÅ
saddr.sin_addr.s_addr = inet_addr(argv[1]); //°Ñµã·ÖÊ®½øÖÆIPת»»³É4×Ö½Ú
//3)°ÑÌ×½Ó×ְ󶨳ɼàÌýÌ×½Ó×Öbind
err = bind(sfd, (struct sockaddr *)&saddr, sizeof(saddr));
if(err < 0)
{
printf("Binding failure\n");
return -1;
}
printf("Binding success\n");
//4)ͨ¹ýÊý¾Ý°ü·¢ËÍ/½ÓÊÕº¯Êý½øÐÐÍøÂçͨÐÅsendto/recvfrom
char buf[65];
while(1)
{
memset(buf, 0, sizeof(buf));
recvfrom(sfd, buf, sizeof(buf)-1, 0, NULL, NULL);
printf("buf = %s", buf);
}
//5)¹Ø±ÕÌ×½Ó×Öclose
close(sfd);
return 0;
}
ÒÔÉÏÄÚÈÝÖ÷ҪʹÓÃÁËsocket¡¢bind¡¢recvfromµÈº¯ÊýʵÏÖÔÚ·þÎñÆ÷ÖÐʵʱ¼à²â´Ó¿Í»§¶Ë·¢À´µÄÐÅÏ¢²¢ÏÔʾ
º¯ÊýÏà¹ØʹÓÃ˵Ã÷ÔÚÉÏÒ»¸öÌû×ÓUDPÍøÂçͨÐÅÖÐ