Unix网络编程(迭代服务器)

#include <stdio.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>

int main(int argc, int *argv[]){
    const int LISTENQ = 5;  // backlog: max conn size
    const int MAXLINE = 255;

    int listenfd, connfd;
    socklen_t len;
    struct sockaddr_in serveraddr, cliaddr;
    char buff[MAXLINE];
    time_t ticks;

    listenfd = socket(AF_INET, SOCK_STREAM,0);
    //bzero(&serveraddr,sizeof(serveraddr));
    memset(&serveraddr,0,sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons(13);    // daytime server

    bind(listenfd, (const struct sockaddr*)&serveraddr, sizeof(serveraddr));

    listen(listenfd, LISTENQ);

    for(;;){
        len = sizeof(cliaddr);
        connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &len);
        printf("connection from %s, port %d\n",
            inet_ntop(AF_INET, &cliaddr.sin_addr, buff, sizeof(buff)),
            ntohs(cliaddr.sin_port));
        ticks = time(NULL);
        snprintf(buff, sizeof(buff),"%.24s\r\n",ctime(&ticks));
        write(connfd, buff, strlen(buff));
        close(connfd);
    }
    //printf("len of sockaddr:%d,%d\n",sizeof(struct sockaddr),
    //      sizeof(struct sockaddr_in));
    return 0;
}

 Python客户端:

import socket 

address = ('192.168.10.67', 13)  
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(address)
data = s.recv(512)
print 'the data received is:',data   

s.close()

 

posted @ 2015-07-29 16:53  庚武  Views(293)  Comments(0Edit  收藏  举报