All pastes #623223 Raw Edit

Untitled

public text v1 · immutable
·published 2007-07-17 13:14 UTC
rendered paste body
/* server */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void)
{
        int sockdesc, newdesc, new;
        sockdesc = socket(AF_INET, SOCK_STREAM, 0);
        if(sockdesc == -1){ perror("socket\n"); exit(1); }
        struct sockaddr_in me;
        struct sockaddr_in friend;
        bzero(&me, sizeof(me)); bzero(&friend, sizeof(friend));
        me.sin_family=AF_INET;
        me.sin_port=htons(8081);
        me.sin_addr.s_addr=htonl(INADDR_ANY);
        if(bind(sockdesc, (struct sockaddr *)&me, sizeof(struct sockaddr))<0){ perror("bind\n"); exit(1); }
        listen(sockdesc, 1);
        int newsize=sizeof(struct sockaddr);
        new = accept(sockdesc, (struct sockaddr *)&friend, &newsize);
        if(new == -1) { perror("accept\n"); exit(1); }

        socklen_t newlen=sizeof(struct sockaddr);
        if(getpeername(sockdesc, (struct sockaddr *)&friend, &newlen)<0){ perror("getpeername\n"); exit(1); }
        printf("IP: %s\n", inet_ntoa(friend.sin_addr));
        printf("PORT: %d\n", ntohs(friend.sin_port));
        close(sockdesc);
        close(newdesc);
        return 0;
}