1. 程式人生 > >socket 映射服務器程序

socket 映射服務器程序

include int see ems urn amp family res size

server

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

        int listenfd;
        listenfd 
= socket(PF_INET,SOCK_STREAM,0); if(listenfd < 0) { printf("creat socket failed\n"); exit(1); } struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port
= htons(5188); servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//host any address if(bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0) { printf("bind fialed\n"); exit(1); } if(listen(listenfd,SOMAXCONN)<0) { printf(
"listen failed\n"); exit(1); } struct sockaddr_in peeraddr; socklen_t peerlen = sizeof(peeraddr); int conn; if((conn=accept(listenfd,(struct sockaddr*)&peeraddr,&peerlen))<0) { printf("accept failed\n"); exit(1); } printf("ip=%s, port=%d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port )); char recvbuf[1024]; while(1) { memset(recvbuf,0,sizeof(recvbuf)); int ret = read(conn,recvbuf,sizeof(recvbuf)); fputs(recvbuf,stdout); write(conn,recvbuf,ret); } close(conn); close(listenfd); return 0; }

client

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

int main(void)
{
        int sock;
        sock = socket(PF_INET,SOCK_STREAM,0);
        if(sock < 0)
        {
                printf("creat socket failed\n");
                exit(1);
        }
        struct sockaddr_in servaddr;
        memset(&servaddr,0,sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        servaddr.sin_port = htons(5188);
        //servaddr.sin_addr.s_addr = htonl(INADDR_ANY);//host any address
        servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

        if(connect(sock,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
        {
                printf("connect failed \n");
                exit(1);
        }

        char sendbuf[1024] = {0};
        char recvbuf[1024] = {0};
        while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL)
        {
                write(sock,sendbuf,strlen(sendbuf));
                read(sock,recvbuf,sizeof(recvbuf));

                fputs(recvbuf,stdout);
                memset(recvbuf,0,sizeof(recvbuf));
        }

        close(sock);
        return 0;
}

socket 映射服務器程序