转载与修改

http://blog.chinaunix.net/uid-14833587-id-76539.html


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>

#define MYPORT 5000

char buf[80];
int main(void)
{
    int sock, new_sd, adrlen, cnt;
    int re_use_addr=1;
    int ret;
    int status;
    pid_t pid;
    pid_t pc;

    struct sockaddr_in myname;
    struct timeval nNetTimeout;
    nNetTimeout.tv_sec = 5;
    nNetTimeout.tv_usec = 0;

    sock = socket(AF_INET, SOCK_STREAM, 0); // 套接字的建立,sock 式套接字描述符号.
    if (sock < 0)
    {
        printf("server socket failure %d\n", errno);
        perror("server: ");
        exit(1);
    }
    myname.sin_family = AF_INET; //建立IPV4通信
    myname.sin_port = htons(MYPORT); //htons是将整型变量从主机字节顺序转变成网络字节顺序,intel 是小端
    myname.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY就是指定地址为0.0.0.0的地址,这个地址事实上表示不确定地址,或“所有地址”、“任意地址”。 一般来说,在各个系统中均定义成为0值。
    bzero(&(myname.sin_zero), 8);// 使字符串的多少位置变为0,这个函数已经不常用了.

    ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&re_use_addr, sizeof(int));
    // SOL_SOCKET 选项定义的层次,另一个是IPPROTO_TCP层次
    // SO_REUSEADDR 允许套接口和一个已在使用中的地址捆绑(参见bind())
    // setsockopt() 函数用于任意类型、任意状态套接口的设置选项值。
    if(ret<0)
    {
        perror("setsockopt:");
        return ret;
    }

    adrlen = sizeof(struct sockaddr_in);
    if (bind(sock, (struct sockaddr *)&myname, adrlen) < 0)
    //bind()用来设置给参数sockfd的socket一个名称。此名称由参数my_addr指向一sockaddr结构,对于不同的socket domain定义了一个通用的数据结构  个人猜想 绑定.
    {
        printf("server bind failure %d\n", errno);
        perror("server: ");
        exit(1);
    }
    if (listen(sock, 5) < 0)
    //listen()用来等待参数s 的socket连线。参数backlog指定同时能处理的最大连接要求,如果连接数目达此上限则client端将收到ECONNREFUSED的错误。Listen()并未开始接收连线,只是设置socket为listen模式,真正接收client端连线的是accept()。通常listen()会在socket(),bind()之后调用,接着才调用accept()。
    {        /* listen函数调用 */
        printf("server listen failure %d\n", errno);
        perror("server: ");
        exit(1);
    }

    /* 忽略子进程的终止  */
//    signal (SIGCHLD, SIG_IGN);
    /*  将服务器置于死循环状态,等待客户端的连接请求的到来。
        实际上,应该用更好的办法来结束这个死循环,在这里这
        个循环是被连接开始信号或者是超级用户终止的。     */

#if 0
    //发送时限
    ret = setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&nNetTimeout, sizeof(nNetTimeout));
    if(ret < 0)
    {
        perror("server");
    }
    //接收时限
    ret = setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&nNetTimeout, sizeof(nNetTimeout));
    if(ret < 0)
    {
        perror("server");
    }
#endif

    while (1)
    {
        if ((new_sd = accept(sock, (struct sockaddr *)&myname, &adrlen)) < 0)
        {
            printf("server accept failure %d\n", errno);
            perror("server: ");
            exit(1);
        }

        pc = fork();
        if(pc<0)
        {
            perror("[server]");
        }
        if (pc == 0)
        {  /* 建立子进程 */
            close (sock);  /* 关闭套接字,因为子进程不再需要它  */

            memset(buf,0,sizeof(buf));
            cnt = recv(new_sd, buf, sizeof(buf),0);
            // recv 从缓冲区拷贝数据.
            if(cnt<0)
            {
                perror("[server]");
            }
            else if(cnt == 0)
            {
                printf(" connection closed by client\n");
            }
            else
            {
                printf("Server got message:[%d]%s\n",cnt,buf);//recv 成功的化就会返回接收到的字节数据
            }

            memset(buf,0,sizeof(buf));
            strcpy(buf, "[dancy]send message to client:");
            cnt = write(new_sd, buf, sizeof(buf));

            close (new_sd); /* close prior to exiting  */
            exit(1);
        }
    }

    close (new_sd); /* close prior to exiting  */
    close (sock);  /* 关闭套接字,因为子进程不再需要它  */
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>

#define SERVER_PORT 5000

char buf[80];
struct sockaddr_in myname;
int main(void)
{
    int sock, adrlen, cnt;
    int ret;
    struct hostent *h;

    if (((h=gethostbyname("192.168.111.45")) == NULL))// 获取ip地址
    {
            herror("gethostbyname");
            exit(1);
    }

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
            printf("client socket failure %d\n", errno);
            perror("client: ");
            exit(1);
    }

    myname.sin_family = AF_INET;
    myname.sin_port = htons(SERVER_PORT);
    myname.sin_addr = *((struct in_addr *)h->h_addr);
    bzero(&(myname.sin_zero), 8);

    ret = connect(sock, (struct sockaddr *) &myname, sizeof(struct sockaddr));
    if(ret<0)
    {
            perror("cannot connect ");
            exit(1);
    }

    memset(buf,0,sizeof(buf));
    strcpy(buf, "[dancy]send message dafdasf123454354我爱你 to server leeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
    cnt = send(sock, buf, strlen(buf),0);
    //send 发送数据
    memset(buf,0,sizeof(buf));
    cnt = read(sock, buf, sizeof(buf));
    //读取数据
    printf("Client got message:[%d]%s\n", cnt,buf);
    exit(0);
}
import socket
import time

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    sock.connect(('192.168.111.45',5000))
    sock.send('send message to server'.encode())
    print( sock.recv(1024))
    sock.close()
import socket
import os
import time

if __name__ == '__main__':
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    sock.bind(("192.168.111.45",5000))
    sock.listen(5)
    while True:
        connection, address = sock.accept()
        print(connection, address)
        try:
            connection.settimeout(5)
            buf =connection.recv(1024)
            print( buf )

            connection.send("send message to client".encode())
        except socket.timeout:
            print( 'time out')

        connection.close()
    sock.close()
posted on 2017-10-30 13:33  HDU李少帅  阅读(270)  评论(0编辑  收藏  举报