---------send to--------
#include "stdio.h"
#include "sys/socket.h"
#include "netinet/in.h"
int main(void)
{
struct sockaddr_in sockin;
int sockId = 0,ret = 0;
char* buf;
sockId = socket(AF_INET,SOCK_DGRAM,0);
if(sockId < 0)
{
printf("Socket Failed!\n");
return 1;
}
memset(&sockin,0x0,sizeof(sockin));
sockin.sin_family = AF_INET;
sockin.sin_port = htons(1234);
sockin.sin_addr.s_addr = inet_addr("192.168.2.4");
//memset(&buf,'A',100);
buf = "This is message from server";
ret = sendto(sockId,buf,100,0,(struct sockaddr *)&sockin,sizeof(sockin));
if(ret != 100)
{
printf("Sendto failed!\n");
return 1;
}
close(sockId);
printf("Sendto succeed!\n");
return 0;
}
-----------receive----------
#include "stdio.h"
#include "sys/socket.h"
#include "netinet/in.h"
int main(void)
{
struct sockaddr_in sockin;
int sockId = 0,ret = 0;
char buf[100];
sockId = socket(AF_INET,SOCK_DGRAM,0);
if(sockId < 0)
{
printf("Socket Failed!\n");
return 1;
}
memset(&sockin,0x0,sizeof(sockin));
sockin.sin_family = AF_INET;
sockin.sin_port = htons(1234);
sockin.sin_addr.s_addr = INADDR_ANY;
ret = bind(sockId,(struct sockaddr *)&sockin,sizeof(sockin));
if(ret < 0)
{
printf("bind failed!\n");
return 1;
}
ret = recvfrom(sockId,buf,100,0,NULL,NULL);
if(ret < 0)
{
printf("Recvfrom failed!\n");
return 1;
}
printf("Recvfrom result=%d\n",ret);
close(sockId);
printf("%s\n",buf);
return 0;
}