afunms

My Software,My Dream—Forge a more perfect NMS product.

c socket programming

---------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;  
}


posted on 2008-03-12 15:51 afunms 阅读(147) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

My Links

News

留言簿(18)

随笔档案

相册

搜索

最新评论

阅读排行榜