1. 程式人生 > >linux tcp socket程式設計初級

linux tcp socket程式設計初級

服務端:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc,char *argv[])
{
    socklen_t  prolen;
    int lfd,cfd;
    int ret;
    char buff[256];
    struct sockaddr_in seraddr,cliaddr;

    if((lfd = socket(AF_INET,SOCK_STREAM,0)) <  0)
        return 0;

    memset(&seraddr,0,sizeof(seraddr));
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(9988);
    seraddr.sin_addr.s_addr = htons(INADDR_ANY);

    if(bind(lfd,(struct sockaddr *)&seraddr,sizeof(seraddr)) < 0 )
    {
        printf("bind error\n");
        goto out;
    }
    if(listen(lfd,20) < 0 )
    {
        printf("listen error\n");
        goto out;
     }

    memset(&cliaddr,0,sizeof(cliaddr));
    prolen = sizeof(cliaddr);
    if((cfd = accept(lfd,(struct sockaddr *)&cliaddr,&prolen)) < 0 )
    {
        printf("accept error\n");
        goto out;
    }
    printf("Recv from clinet %s\n",inet_ntoa(cliaddr.sin_addr));
	 while(1)
    {
        memset(buff,0,256);
        ret = recv(cfd,buff,256,0);
        if(ret <= 0 )
           break;
        printf("*****************msg:%s\n",buff);
    }

out:
    close(lfd);
    return 0;
}

客戶端:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>

int main(int argc,char *argv[])
{
    socklen_t  prolen;
    int cfd;
    int ret;
    char buff[256];
    struct sockaddr_in seraddr;

    if((cfd = socket(AF_INET,SOCK_STREAM,0)) <  0)
        return 0;

    memset(&seraddr,0,sizeof(seraddr));
    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(9988);
    seraddr.sin_addr.s_addr = inet_addr("192.168.11.102");


    if(connect(cfd,(struct sockaddr *)&seraddr,sizeof(seraddr)) < 0 )
    {
       printf("conn error\n");
       goto out;
    }

    while(1)
    {
        memset(buff,0,256);
        sprintf(buff,"helloworld");
        ret = send(cfd,buff,strlen(buff),0);
        if(ret <= 0 )
        {
           printf("send error\n");
           break;
         }
         printf("send success\n");
         sleep(2);
    }

out:
    close(cfd);
    return 0;
}