编程语言
首页 > 编程语言> > 网络编程

网络编程

作者:互联网

服务器端:

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <ctype.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <strings.h>

#define SERVER_PORT 6666
#define SERVER_IP "127.0.0.1"

int main()
{
    int lfd=socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family= AF_INET;
    server_addr.sin_port=htons(6666);
    server_addr.sin_addr.s_addr= htonl(INADDR_ANY);

    bind(lfd,(struct sockaddr*) &server_addr, sizeof(server_addr));

    listen(lfd,32);
    int cfd;
    struct sockaddr_in client_addr;
    socklen_t client_addr_len=sizeof(client_addr);
    cfd=accept(lfd,(struct sockaddr*) &client_addr, &client_addr_len);
    char client_ip_buf[BUFSIZ];
    inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,client_ip_buf, sizeof(client_ip_buf));
    printf("client ip: %s   client port: %d\n", client_ip_buf, ntohs(client_addr.sin_port));
    
    char buf[BUFSIZ];
    while(1){
        int n=read(cfd,buf,sizeof(buf));
        int i;
        for(i=0;i<n;i++){
            buf[i]=toupper(buf[i]);
        }
        write(cfd,buf,n);
    }
    close(lfd);
    close(cfd);

    return 0;
}

客户端:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>    // struct sockaddr_in
#include <string.h>

#define SERVER_IP "127.0.0.1"

int main()
{
    int cfd;
    cfd=socket(AF_INET,SOCK_STREAM,0);
    
    struct sockaddr_in server_addr;

    memset(&server_addr,0,sizeof(server_addr));
    server_addr.sin_family=AF_INET;
    server_addr.sin_port=htons(6666);
    inet_pton(AF_INET,SERVER_IP, &server_addr.sin_addr.s_addr);
    connect(cfd,(struct sockaddr*) &server_addr, sizeof(server_addr));

    char buf[BUFSIZ];
    while(1){
        fgets(buf,sizeof(buf),stdin);
        write(cfd,buf,strlen(buf));

        int n;
        n=read(cfd,buf,sizeof(buf));
        write(STDOUT_FILENO,buf,n);
    }
    close(cfd);
    return 0;
}

 

标签:addr,cfd,编程,网络,server,client,include,buf
来源: https://www.cnblogs.com/FEIIEF/p/13040259.html