tcp局域网

服务端 server.c
#include <stdio.h>
#include <string.h>
#include <netinet/in.h>

#define PORT 9999

main()
{
    struct sockaddr_in client,server;
    int s,ns,clientlen,recievelen;
    char buf[256];

    s=socket(AF_INET,SOCK_STREAM,0);
    memset((char *)&server,sizeof(server),0);
    server.sin_family=AF_INET;
    server.sin_port=htons(PORT);
    server.sin_addr.s_addr=INADDR_ANY;
    bind(s,(struct sockaddr *)&server,sizeof(server));
    listen(s,1);
    clientlen=sizeof(client);
    ns=accept(s,(struct sockaddr *)&client,&clientlen);
    for(;;)
    {
        recievelen=recv(ns,buf,sizeof(buf),0);
        if(recievelen==0)
            break;
        printf("对方说: %s\n",buf);
        send(ns,buf,recievelen,0);
    }
    close(ns);
    close(s);
}

客户端 client.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>

#define PORT 9999
#define HOST_ADDR "192.168.8.35"

main()
{
    struct sockaddr_in server;
    int s,ns;
    int recievelen,buflen;
    char buf1[256],buf2[256];

    s=socket(AF_INET,SOCK_STREAM,0);
    server.sin_family=AF_INET;
    server.sin_port=htons(PORT);
    server.sin_addr.s_addr=inet_addr(HOST_ADDR);
    if(connect(s,(struct sockaddr *)&server,sizeof(server))<0)
    {
        perror("connect()");
        return;
    }
    for(;;)
    {
        printf("输入内容:");
        gets(buf1);
        buflen=strlen(buf1);
        if(buflen==0)
            break;
        send(s,buf1,buflen+1,0);
        recv(s,buf2,sizeof(buf2),0);
        printf("你说: %s\n",buf2);
    }
    close(s);
}

 

posted on 2012-12-07 11:57  小风儿_xf  阅读(203)  评论(0编辑  收藏  举报

导航