int accept_connection(int listener) { int newfd; socklen_t addrlen; sockaddr_storage remoteaddr; char remoteIP[INET6_ADDRSTRLEN]; addrlen = sizeof(remoteaddr); newfd = accept(listener,(sockaddr*)&remoteaddr, &addrlen); if (newfd == -1) { perror("Accept"); return 0; } printf("New connection from %s on " "socket %d\n", inet_ntop(remoteaddr.ss_family, get_in_addr((sockaddr*)&remoteaddr), remoteIP, INET6_ADDRSTRLEN), newfd); return newfd; }
char *receive_msg(int sockfd) { char *buf = (char *) malloc (sizeof(char) * 1000); int numbytes, new_fd; struct sockaddr_storage their_addr; socklen_t sin_size; char s[INET6_ADDRSTRLEN]; sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); close(sockfd); numbytes = recv(new_fd, buf, MAXDATASIZE-1, 0); buf[numbytes] = '\0'; close(new_fd); return buf; }
int aceptarNuevaConexion(int listener){ int new_socket; struct sockaddr_storage remoteaddr; // client address socklen_t addrlen; char remoteIP[INET6_ADDRSTRLEN]; // handle new connections addrlen = sizeof remoteaddr; new_socket = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen); puts("Conexion aceptada"); if (new_socket == -1) { perror("accept"); } printf("Nueva conexion %s en socket %d\n", inet_ntop(remoteaddr.ss_family, get_in_addr((struct sockaddr*)&remoteaddr), remoteIP, INET6_ADDRSTRLEN), listener); return new_socket; }
int send_to_host(char *msg, char *remotehost) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; getaddrinfo(remotehost, PORT, &hints, &servinfo); sockfd = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol); connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen); inet_ntop(servinfo->ai_family, get_in_addr((struct sockaddr *)servinfo->ai_addr), s, sizeof s); freeaddrinfo(servinfo); send(sockfd, msg, strlen(msg), 0); close(sockfd); return 0; }
int AcceptConnection(int sockfd) { struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; int new_fd, flags; char s[INET6_ADDRSTRLEN]; //first set sockfd to nonblocking if ((flags = fcntl(sockfd, F_GETFL, 0)) == -1) flags = 0; fcntl(sockfd, F_SETFL, flags | O_NONBLOCK); sin_size = sizeof(their_addr); new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) return new_fd; //no connection inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof(s)); printf("server: got connection from %s\n", s); return new_fd; }
/* <doc> * bool multicast_leave(int mcast_fd, struct sockaddr_in group_ip) * Client leaves the multicast group address. This function takes * parameter as * - multicast group address * - Multicast FD on which client is bound * * </doc> */ bool multicast_leave(int mcast_fd, struct sockaddr_in group_ip) { struct ip_mreq group; char group_ip_address[INET6_ADDRSTRLEN]; //inet_ntop(AF_INET, &(group_ip), group_ip_address, INET_ADDRSTRLEN); inet_ntop(AF_INET, get_in_addr((struct sockaddr *)&(group_ip)), group_ip_address, INET6_ADDRSTRLEN); group.imr_multiaddr.s_addr = inet_addr(group_ip_address); group.imr_interface.s_addr = INADDR_ANY; if(setsockopt(mcast_fd, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char *)&group, sizeof(group)) < 0) { PRINT("Group Ip Address = %s & mcast_fd = %d",group_ip_address, mcast_fd); perror("Leaving multicast group error"); exit(1); } close(mcast_fd); return TRUE; }
int connect( char * address ) { memset( &hints, 0, sizeof( hints ) ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if( ( rv = getaddrinfo( address, PORT, &hints, &servinfo ) ) != 0 ) { fprintf( stderr, "getaddrinfo: %s\n", gai_strerror( rv ) ); return 1; } for( p = servinfo; p != NULL; p = p->ai_next ) { if( ( sockfd = socket( p->ai_family, p->ai_socktype, p->ai_protocol ) ) == -1 ) { perror( "client: socket" ); continue; } if( connect( sockfd, p->ai_addr, p->ai_addrlen ) == -1 ) { close( sockfd ); perror( "client: connect" ); continue; } break; } if( p == NULL ) { fprintf( stderr, "client: failed to connect\n" ); return 2; } inet_ntop( p->ai_family, get_in_addr( ( struct sockaddr *)p->ai_addr ), s, sizeof( s ) ); freeaddrinfo( servinfo ); return sockfd; }
static int dns_query_execute(char* query, char* resp, u_int resp_len) { struct addrinfo *result = NULL, *cur = NULL; int rc; struct addrinfo hint; memset(&hint, 0 , sizeof(hint)); /* hint.ai_family = AF_UNSPEC; - zero anyway */ /* Needed. Or else we will get each address thrice (or more) * for each possible socket type (tcp,udp,raw...): */ hint.ai_socktype = SOCK_STREAM; // hint.ai_flags = AI_CANONNAME; rc = getaddrinfo(query, NULL /*service*/, &hint, &result); if(rc) { // The host is not blacklisted if(rc == EAI_NONAME) return 1; // That's another error snprintf(resp, resp_len, "%s [errno=%d]", gai_strerror(rc), rc); return 0; } cur = result; while (cur) { char dotted[INET6_ADDRSTRLEN]; inet_ntop(cur->ai_family, get_in_addr((struct sockaddr *)cur->ai_addr), dotted, sizeof(dotted)); snprintf(resp, resp_len, "%s", dotted); cur = cur->ai_next; if(cur) { snprintf(resp, resp_len, "Multiple address returned. Something is wrong!"); return 0; } } return 2; }
static void accept_cb(struct ev_loop *loop, ev_io *w, int revents) { char s[INET6_ADDRSTRLEN]; jrpc_Connection_t * connection_watcher; jrpc_Server_t * server = (jrpc_Server_t *)w->data; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size = sizeof(their_addr); connection_watcher = malloc(sizeof(jrpc_Connection_t)); if(connection_watcher == NULL) { perror("malloc"); return; } connection_watcher->fd = accept(w->fd, (struct sockaddr *) &their_addr, &sin_size); if (connection_watcher->fd == -1) { perror("accept"); free(connection_watcher); } else { if (server->debug_level) { inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *) &their_addr), s, sizeof s); printf("server: got connection from %s\n", s); } ev_io_init( &(connection_watcher->io), connection_cb, connection_watcher->fd, EV_READ); // Copy pointer to jrpc_Server_t connection_watcher->io.data = w->data; // Allocate buffer connection_watcher->buffer_size = JRPC_CONNECTION_BUFFER_SZ; connection_watcher->buffer = calloc(1, JRPC_CONNECTION_BUFFER_SZ); connection_watcher->pos = 0; // Copy debug_level, jrpc_Connection_t has no pointer to jrpc_Server_t connection_watcher->debug_level = server->debug_level; ev_io_start(loop, &connection_watcher->io); } }
int initialize_TCP_client(char * servername, char * portnum){ struct addrinfo hints, *p,*servinfo; int rv, sockfd; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(servername, portnum, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { perror("client: connect"); close(sockfd); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); exit(2); } //Report the info of the client side inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); // all done with this structure freeaddrinfo(servinfo); return sockfd; }
int TCPClient::connect ( const char * ip, const char * port ) { int rv; char s[INET6_ADDRSTRLEN]; addrinfo hints, *servinfo, *p; try { memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo( ip, port, &hints, &servinfo)) != 0) { throw "getaddrinfo: " + std::string ( gai_strerror(rv) ); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if (tcpSocket(p->ai_family, p->ai_protocol) == -1) { continue; } if (::connect(socketDesc, p->ai_addr, p->ai_addrlen) == -1) { continue; } break; } if (p == NULL) { throw "failed to connect"; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); freeaddrinfo(servinfo); // all done with this structure } catch ( LogString e ) { } return 0; }
void _peer_accept(void) { st_netfd_t client; struct sockaddr from; int fromlen = sizeof(from); struct peer_info *peer_info; peer_info = &peer_list[self_index]; // 每个 Peer 的主回环 while ((client = st_accept(peer_info->rpc_fd, &from, &fromlen, ST_UTIME_NO_TIMEOUT)) != NULL) { LOG("[%d] 收到一个 RPC 互联请求\n", self_index); st_netfd_setspecific(client, get_in_addr(&from), NULL); if (st_thread_create(_handle_peer_interconnect, client, 0, 0) == NULL) ERR("[%d] failed to create the client thread: %s\n", self_index, strerror(errno)); } LOG("[%d] 完成了当前 Peer 的主循环: %s\n", self_index, strerror(errno)); st_netfd_close(peer_info->rpc_fd); }
int connect_to_host(char *host, int port, char* buffer, int buflen) { int portlen, r, newfd; struct addrinfo hints, *servinfo, *p; char *portstr; memset(&hints, 0, sizeof hints); // make sure the struct is empty hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6 hints.ai_socktype = SOCK_STREAM; // TCP stream sockets portlen = snprintf(NULL, 0, "%d", port); portstr = (char *)emalloc(portlen+1); snprintf(portstr, portlen+1, "%d", port); if ((r = getaddrinfo(host, portstr, &hints, &servinfo)) != 0){ fprintf(stderr,"getaddrinfo: %s\n", gai_strerror(r)); } efree(portstr); for(p = servinfo; p != NULL; p = p->ai_next) { if ((newfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("socket"); continue; } if (connect(newfd, p->ai_addr, p->ai_addrlen) == -1) { close(newfd); // perror("connect"); continue; } break; } if (p == NULL) newfd = -1; else if (buffer != NULL) inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), buffer, buflen); freeaddrinfo(servinfo); return newfd; }
//helper function to establish a connection to the host //does NOT call getaddrinfo, which must be supplied to the function //through the cache struct int establish_tcp_client(cache_t cache) { int socket_fd; char s[INET6_ADDRSTRLEN]; if ( (socket_fd = socket(cache->tcpinfo->ai_family, cache->tcpinfo->ai_socktype, cache->tcpinfo->ai_protocol)) == -1) { printf("socket error.\n"); exit(1); } printf("Connecting...\n"); if ( connect(socket_fd, cache->tcpinfo->ai_addr, cache->tcpinfo->ai_addrlen) == -1) { printf("connection refused.\n"); exit(1); } inet_ntop(cache->tcpinfo->ai_family, get_in_addr((struct sockaddr *)cache->tcpinfo->ai_addr), s, sizeof s); printf("Client: connecting to %s\n", s); return socket_fd; }
int waitForConnections(RTSPServer *server) { pthread_t thread; // Thread to be created struct sockaddr_storage their_addr; // connector's address information int new_fd; socklen_t sin_size; char s[INET6_ADDRSTRLEN]; RTSPClient *clientInfo; while (1) { sin_size = sizeof their_addr; new_fd = accept(server->sockfd, (struct sockaddr *) &their_addr, &sin_size); if (new_fd == -1) { printf("Got bad socket fd in wait for connections"); continue; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *) &their_addr), s, sizeof s); printf("server: got connection from %s\n", s); clientInfo = (RTSPClient*) malloc(sizeof(RTSPClient)); clientInfo->connections_list = (OpenCloudConnection*) malloc(sizeof(OpenCloudConnection)); clientInfo->connections_list->host = (char*) malloc(sizeof(char)); pthread_mutex_init(&clientInfo->clientLock, NULL); clientInfo->playback_timer = (PlaybackTimer*) malloc(sizeof(PlaybackTimer)); if (!clientInfo) { printf("There wasn't enough memory to fufill the connection.\n"); continue; } clientInfo->socket = new_fd; pthread_create(&thread, NULL, handleClientConnection, (void *) clientInfo); printf("Starting thread...\n"); pthread_detach(thread); } return 0; }
int accept_client(int serv_sock) { int reply_sock_fd = -1; socklen_t sin_size = sizeof(struct sockaddr_storage); struct sockaddr_storage client_addr; char client_printable_addr[INET6_ADDRSTRLEN]; // accept a connection request from a client // the returned file descriptor from accept will be used // to communicate with this client. if ((reply_sock_fd = accept(serv_sock, (struct sockaddr *)&client_addr, &sin_size)) == -1) { printf("socket accept error\n"); } else { // here is only info only, not really needed. inet_ntop(client_addr.ss_family, get_in_addr((struct sockaddr *)&client_addr), client_printable_addr, sizeof client_printable_addr); printf("server: connection from %s at port %d\n", client_printable_addr, ((struct sockaddr_in*)&client_addr)->sin_port); } return reply_sock_fd; }
int initialize_UDP_client(char * servername_udp, char * portnum_udp){ struct addrinfo hints_udp, *p_udp,*servinfo_udp; int rv_udp,sockfd_udp; char s_udp[INET6_ADDRSTRLEN]; memset(&hints_udp, 0, sizeof hints_udp); hints_udp.ai_family = AF_UNSPEC; hints_udp.ai_socktype = SOCK_DGRAM; if ((rv_udp = getaddrinfo(servername_udp, portnum_udp, &hints_udp, &servinfo_udp)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv_udp)); exit(1); } // loop through all the results and make a socket for(p_udp = servinfo_udp; p_udp != NULL; p_udp = p_udp->ai_next) { if ((sockfd_udp = socket(p_udp->ai_family, p_udp->ai_socktype, p_udp->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p_udp == NULL) { fprintf(stderr, "talker: failed to create socket\n"); exit(2); } connect(sockfd_udp, p_udp->ai_addr, p_udp->ai_addrlen); //Report the info of the client side inet_ntop(p_udp->ai_family, get_in_addr((struct sockaddr *)p_udp->ai_addr), s_udp, sizeof s_udp); printf("talker: connecting to %s\n", s_udp); // all done with this structure freeaddrinfo(servinfo_udp); return sockfd_udp; }
int boss::Socket::send_to(const void *msg, size_t len, uint16_t port, const char *host_address /*= NULL*/ , int flags /* = 0 */ ) { struct sockaddr toaddr; struct sockaddr_in *p = (struct sockaddr_in *) &toaddr; bzero(&toaddr, sizeof(struct sockaddr)); p->sin_family = AF_INET; if (host_address == NULL) { p->sin_addr.s_addr = htonl(INADDR_BROADCAST); } else { get_in_addr(host_address, p->sin_addr, "send_to"); } p->sin_port = htons(port); return send_to(msg, len, toaddr, sizeof(toaddr), flags); }
int transfer(int from, int to, struct sockaddr_storage their_addr, socklen_t addr_len, struct sockaddr* res) { char buf[MAXDATASIZE]; int disconnected = 0; char s[INET6_ADDRSTRLEN]; size_t bytes_read; bytes_read = recvMsg(to, buf); printf("listener: got connection from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); if (bytes_read == 0) { disconnected = 1; memset(buf, 0, sizeof buf); } if(sendMessageUDP2(from, buf, res, addr_len) == -1) { disconnected = 1; memset(buf, 0, sizeof buf); } /*else { bytes_written = recvMsg(to, buf); if (bytes_written == -1) { disconnected = 1; memset(buf, 0, sizeof buf); } if ((numbytes = recvfrom(from, buf, MAXDATASIZE-1 , 0, res, &addr_len)) == -1) { perror("recvfrom"); exit(1); } }*/ return disconnected; }
timestamp_t NetCom::rxTs(NetComDat net){ char s[INET6_ADDRSTRLEN]; char buff[6] = {'\0'};; int numbytes; sockaddr_storage their_addr = net.their_addr; socklen_t addr_len = sizeof (their_addr); sockaddr_in sa = *(struct sockaddr_in *)&their_addr; if ((numbytes = recvfrom(net.sockfd, &buff, 20 , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } printf("listener: got packet from %s\n", inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr), s, sizeof s)); return 0; }
/*Will create a socket connection to the dsanode with id: dsanode_ids[index] ** */ int connectToDsanode(int index){ int sockfd; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(dsanode_ids[index].ip, dsanode_ids[index].port, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1){ perror("gateway: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("gateway: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "gw: failed to connect\n"); exit(2); } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),s, sizeof s); printf("GW: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure return sockfd; }
int main(int argc, char *argv[]) { char temp[50]="available"; char prefix[50]="authenticate "; int sockfd, numbytes; FILE *fp; fp = fopen("patient2.txt","r"); char p1un[20]; char bk[10]=" "; char p1pw[20]; fscanf(fp,"%s %s",p1un,p1pw); fclose(fp); strcat(p1un,bk); strcat(prefix,p1un); strcat(prefix,p1pw); char buf[100]; char ins[20]; FILE *fp2; fp2 = fopen("patient2insurance.txt","r"); fscanf(fp2,"%s",ins); strcat(p1un,ins); struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo("localhost", PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); freeaddrinfo(servinfo); if (send(sockfd, prefix, 50, 0) == -1){ perror("send"); } //get port number struct sockaddr_in addr; memset(&addr,0,sizeof(addr)); int len = sizeof addr; getsockname(sockfd, (struct sockaddr *)&addr, (socklen_t *)&len); char cip[20]; inet_ntop(AF_INET, &addr.sin_addr, cip, sizeof cip); int port=addr.sin_port; printf("Phase 1: Patient 2 has TCP port number %d and IP address %s.\n",port,cip); printf("Phase 1: Authentication request from Patient 2 with username %sand password %s has been sent to the Health Center Server.\n",p1un,p1pw); //!!! char buf2[100]; if ((numbytes = recv(sockfd, buf2, 100, 0)) == -1) { perror("recv"); exit(1); } buf2[numbytes] = '\0'; printf("Phase 1: Patient 2 authentication result: %s.\n",buf2); printf("Phase 1: End of Phase1 for Patient1.\n"); //phase1 if (send(sockfd, temp, 50, 0) == -1){ perror("send"); } if ((numbytes = recv(sockfd, buf, 100, 0)) == -1) { perror("recv"); exit(1); } buf[numbytes] = '\0'; printf("Phase 2: The following appointments are available for Patient 2:\n"); printf("%s\n",buf); char a[100]; printf("Phase 2: Please enter the preferred appointment index and press enter: "); gets(a); FILE *pout; pout=fopen("out.txt","w"); fprintf(pout,"%s\n",a); if (send(sockfd, a, 100, 0) == -1){ perror("send"); } char buf1[100]; if ((numbytes = recv(sockfd, buf1, 100, 0)) == -1) { perror("recv"); exit(1); } buf1[numbytes] = '\0'; printf("Phase 2: The requested appointment is available and reserved to Patient 2. The assigned doctor port number is %s\n",buf1); close(sockfd); //UDP memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; if ((rv = getaddrinfo("127.0.0.1", buf1, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and make a socket for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("talker: socket"); continue; } break; } if (p == NULL) { fprintf(stderr, "talker: failed to bind socket\n"); return 2; } freeaddrinfo(servinfo); if ((numbytes = sendto(sockfd, p1un, 20, 0, p->ai_addr, p->ai_addrlen)) == -1) { perror("talker: sendto");} struct sockaddr_in addrudp; memset(&addrudp,0,sizeof(addrudp)); int lenudp = sizeof addrudp; getsockname(sockfd, (struct sockaddr *)&addrudp, (socklen_t *)&lenudp); inet_ntop(AF_INET, &addrudp.sin_addr, cip, sizeof cip); int portudp=addrudp.sin_port; printf("Phase 3: Patient 2 has a dynamic UDP port number %d and IP address %s.\n",portudp,cip); printf("Phase 3: The cost estimation request from Patient 2 with insurance plan %s has been sent to the doctor with port number %s and IP address %s.\n",ins,buf1,cip); char buf3[100]; if ((numbytes = recvfrom(sockfd, buf3, 100 , 0, NULL, NULL)) == -1) { perror("recvfrom"); exit(1); } buf3[numbytes] = '\0'; char name[10]; if(strcmp(buf1,"41414")==0){ memcpy(name, "doctor1", 10); } else{memcpy(name, "doctor2", 10);} printf("Phase 3: Patient 2 receives $%s estimation cost from doctor with port number %s and name %s.\n",buf3,buf1,name); close(sockfd); printf("Phase 3: End of Phase 3 for Patient 2.\n"); return 0; }
int main(int argc, char *argv[]) { /* Program Variable Define & Initialization */ int sockfd,numbytes; //socket file discriptor struct addrinfo hints, *servinfo, *p; int rv,choice,len; char ch; FILE *fp,*fo; char s[INET6_ADDRSTRLEN]; //hold the ipaddress // if no command line argument supplied if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); //just exit } memset(&hints, 0, sizeof hints); // fill memmory with a constant byte and returns a pointer to the memmory area hints hints.ai_family = AF_UNSPEC; // allow IpV4 or IpV6 adderess domain hints.ai_socktype = SOCK_STREAM; // fo socket stream // getaddrinfo()= returns a list of address structure. /* Given node(NULL) and service(Port), which identify an Internet host and a service, getaddrinfo() returns one or more addrinfo structures, each of which contains an Internet address that can be specified in a call to bind or connect */ // argv[1]= return 1 ipaddress if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } //socket is to create an endpoint for communcation. // servinfo->ai_family argument select the protocol family which will be used for communcation............. // servinfo->ai_socktype, type of socket................................................................... // servinfo->ai_protocol specify the particular to be used with socket..................................... if (sockfd = socket(servinfo->ai_family, servinfo->ai_socktype,servinfo->ai_protocol)){ perror("client: socket"); } /* inet_ntop - convert IPv4 and IPv6 addresses from binary to text form their_addr.ss_family This argument shall specify the family of the address. This can be AF_INET [IP6] [Option Start] or AF_INET6. [Option End] */ /* get_in_addr((struct sockaddr *)&their_addr argument points to a buffer holding an IPv4 address if the af argument is AF_INET, [IP6] [Option Start] or an IPv6 address if the af argument is AF_INET6; [Option End] the address must be in network byte order */ /* s,argument points to a buffer where the function stores the resulting text string; it shall not be NULL.*/ /* sizeof(s) argument specifies the size of this buffer, which shall be large enough to hold the text string (INET_ADDRSTRLEN characters for IPv4, [IP6] [Option Start] INET6_ADDRSTRLEN characters for IPv6). [Option End] */ inet_ntop(servinfo->ai_family, get_in_addr((struct sockaddr *)servinfo->ai_addr),s, sizeof(s)); printf("client: connecting to: %s\n", s); /* The connect() system call connects the socket referred to by the file descriptor sockfd to the address specified by addr. The addrlen argument specifies the size of addr. The format of the address in addr is determined by the address space of the socket sockfd; */ /* If the connection or binding succeeds, zero is returned. On error, -1 is returned, and errno is set appropriately. */ if (connect(sockfd, servinfo->ai_addr, servinfo->ai_addrlen) == -1){ close(sockfd); perror("client: connect"); return 0; } freeaddrinfo(servinfo); while(1) { printf("\n *****************************************************\n"); printf(" Enter your choice:\n"); printf(" For uploading: 1\n For downloading: 2\n For delete: 3\n For exit: 4\n "); scanf("%d",&choice); switch(choice) { case 1: send(sockfd,"1",1,0); video_uploading(sockfd,fp); break; case 2: send(sockfd,"2",1,0); video_downloading(sockfd,fo); break; case 3: send(sockfd,"3",1,0); video_delete(sockfd,fp); break; case 4: send(sockfd,"4",1,0); termination(sockfd,s); exit(1); break; default: printf("wrong choice"); break; } } close(sockfd); return 0; }
bool Server::accept_connection() { while (1) { // main accept() loop sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size); if (new_fd == -1) { error("accept"); return false; } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *) &their_addr), s, sizeof s); cout << "server: got connection from " << s << endl; if (!fork()) { // this is the child process close(sockfd); // child doesn't need the listener cout << "waiting for HTTP request" << endl; char buf_req[MAXREQUESTSIZE]; char buf_rest[MAXREQUESTSIZE]; while (true) { // request line detection char received_chunk[MAXDATASIZE]; memset(received_chunk, 0, MAXDATASIZE); receive_data(received_chunk, MAXDATASIZE); // receive request line // cout << "\treceived 1 : \"" << received_chunk << "\"" << endl; string s = received_chunk; int pos = s.find("\r\n", 0); if (pos != string::npos) { string s1, s2; s1 = s.substr(0, pos); s2 = s.substr(pos); strcpy(buf_req, s1.c_str()); strcpy(buf_rest, s2.c_str()); // cout << "\tbuf_req: \"" << buf_req << "\"" << endl; // cout << "\tbuf_rest: \"" << buf_rest << "\"" << endl; break; } else { strcat(buf_req, received_chunk); } } // find out whether the received request is GET or POST vector<string> v; FileHandler::split(buf_req, ' ', v); if (v[0].compare("GET") == 0) { // GET request detected cout << "GET request detected" << endl; cout << "###################################" << endl << buf_req; string file = WORKINGDIRECTORY + v[1]; while (true) { string s(buf_rest); // cout << "\"" << s << "\"" << endl; int pos = s.find("\r\n\r\n", 0); if (pos != string::npos) { // we reached the end of the GET request, discard the rest string headers; headers = s.substr(0, pos); strcat(buf_rest, headers.c_str()); cout << s << "###################################" << endl; break; } char received_chunk[MAXDATASIZE]; memset(received_chunk, 0, MAXDATASIZE); receive_data(received_chunk, MAXDATASIZE); // receive the rest of the request strcat(buf_rest, received_chunk); } cout << "server: requesting file: " << file << endl; //Check for file existence //File exists if (FileHandler::fexists(file)) { cout << "Exists" << file << endl; //Send File ifstream file_stream; FileHandler::open_file_to_read(&file_stream, file); if (!file_stream.is_open()) { error("Could not open file"); return false; } int file_size = FileHandler::get_file_size(&file_stream); cout << "sending actual file..." << endl; const char* message = construct_message(200).c_str(); send_data(message); send_file(file_size, &file_stream); cout << "file was sent successfully" << endl; } //File doesn't exist else { cout << "Doesn't Exist" << endl; string not_found = construct_message(404); if (send(new_fd, not_found.c_str(), strlen(not_found.c_str()), 0) == -1) error("send"); } } else if (v[0].compare("POST") == 0) { // POST request detected cout << "POST request detected" << endl; cout << "###################################" << endl << buf_req; string file_name = WORKINGDIRECTORY+v[1]; string file_size; bool valid_request = false; char file[MAXREQUESTSIZE]; ///////////////////////////////////////////////// //Getting headers while (true) { string s(buf_rest); // cout << s.length()<<"\"" << s << "\"" << endl; int pos = s.find("\r\n\r\n", 0); if (pos != string::npos) { // we reached the end of the POST request, get the length from the headers and receive the file string headers; headers = s.substr(0, pos); cout<<"ABO:\""<<headers<<"\""<<endl; char header_char_arr [MAXREQUESTSIZE]; strcpy(header_char_arr,headers.c_str()); // extract Content-length from the headers, else report a bad request v.clear(); cout << "\theaders: " << header_char_arr << endl; FileHandler::split_string(header_char_arr, "\r\n", v); for (int i = 0; i < v.size();i++) { vector<string> v2; FileHandler::split(v[i],':',v2); if (v2.size() > 0 && v2[0].compare("Content-Length") == 0) { // found Content-length header, request is valid file_size = v2[1]; valid_request = true; break; } } if (!valid_request) { string message = construct_message(400); send_data(message.c_str()); } else { //Begining of file string temp = ""; cout<<"LL:"<<pos<<" "<<s<<endl; temp = s.substr(pos + 4); cout<<"TEMP:\""<<temp<<"\""<<endl; strcpy(file, temp.c_str()); // strcat(buf_rest, headers.c_str()); int size_int = atoi(file_size.c_str()); cout << "\tsize: " << size_int << endl; cout << s << "###################################" << endl; // int size_written = FileHandler::create_file_from_buf(file_name, file, strlen(file),size_int); FileHandler::concat_to_existing_file(file_name,file,strlen(temp.c_str())); // cout<<":::"<<size_int<<"::"<<size_written<<endl; cout<<"FILE: "<<sizeof(file)<<" Written: "<<strlen(temp.c_str())<<" size int: "<<size_int<<endl; if((receive_file(file_name, size_int-strlen(temp.c_str()))) == false) { cout << "server: An error has occurred and the client may have disconnected" << endl; } cout<<"EEEEEEEEEEEEEEEEEEEEEE"<<endl; string message = construct_message(200); send_data(message.c_str()); } break; } char received_chunk[MAXREQUESTSIZE]; memset(received_chunk, 0, MAXREQUESTSIZE); receive_data(received_chunk, MAXREQUESTSIZE); // receive the rest of the request strcat(buf_rest, received_chunk); } ///////////////////////////////////////////////// } else { //neither // return 400 bad request } close(new_fd); return true; } close(new_fd); // parent doesn't need this } }
int main(int argc, char *argv[]) { int sockfd, numbytes; char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; if (argc != 2) { fprintf(stderr,"usage: client hostname\n"); exit(1); } memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; if ((rv = getaddrinfo(argv[1], PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); freeaddrinfo(servinfo); // all done with this structure uint32_t len = 0; read(sockfd, &len, sizeof(len)); len = len >= MAXDATASIZE ? MAXDATASIZE - 1 : len < 0 ? 0 : len; printf("client: received %d bytes\n\n", len); int totalRead = 0; buf[len] = '\0'; while(totalRead != len) { totalRead += read(sockfd, &buf[totalRead], len - totalRead); } printf("%s\n", buf); close(sockfd); return 0; }
void listener(char *ip, int *port) { int sockfd; struct addrinfo hints, *servinfo, *p; int rv; int numbytes; struct sockaddr_storage their_addr; char buf[MAXBUFLEN]; socklen_t addr_len; uint32_t packet[2]; char port_s[100]; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; snprintf(port_s, 100, "%d", BROADCAST_PORT); if ((rv = getaddrinfo(NULL, port_s, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("listener: socket"); continue; } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("listener: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "listener: failed to bind socket\n"); exit(2); } freeaddrinfo(servinfo); addr_len = sizeof their_addr; int done = 0; while (!done) { if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } else if (numbytes == sizeof(packet)) { //"listener: got packet from %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), ip, INET6_ADDRSTRLEN); memcpy(&packet, buf, sizeof(packet)); if (ntohl(packet[0]) == BCP_CODE) { *port = ntohl(packet[1]); done = 1; } } } close(sockfd); }
void client(char *ip, int *port, char *path) { int sockfd;//, numbytes; char buf[MAXBUFLEN]; struct addrinfo hints, *servinfo, *p; int rv; char s[INET6_ADDRSTRLEN]; int size; FILE *ft; uint32_t filename_size; size_t total; char port_s[100]; char *filename; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; snprintf(port_s, 100, "%d", *port); if ((rv = getaddrinfo(ip, port_s, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } // loop through all the results and connect to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("client: socket"); continue; } if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); exit(2); } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); freeaddrinfo(servinfo); ft = fopen(path, "rb"); if (ft == NULL) { perror("Cannot open file"); exit(1); } filename = basename(path); filename_size = strlen(filename); filename_size = htonl(filename_size); memcpy(buf, &filename_size, sizeof(filename_size)); memcpy(&buf[sizeof(filename_size)], filename, strlen(filename)); if (send(sockfd, buf, sizeof(int)+strlen(filename), 0) == -1) perror("send"); total = 0; while (!feof(ft)) { size = fread(&buf, 1, MAXBUFLEN, ft); total += size; printf("\rSent: %zu", total); if (send(sockfd, buf, size, 0) == -1) perror("send"); } printf("\nFile sent.\n"); close(sockfd); fclose(ft); }
void server(int port) { int sockfd, new_fd; struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; int numbytes; char buf[MAXBUFLEN]; char filename[MAXNAMELEN]; uint32_t filename_size; FILE *ft; size_t total; char port_s[100]; char overwrite; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; snprintf(port_s, 100, "%d", port); if ((rv = getaddrinfo(NULL, port_s, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); exit(1); } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(2); } freeaddrinfo(servinfo); if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("accept"); } inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); printf("Incoming connection from: %s\n", s); numbytes = recv_full(new_fd, &filename_size, sizeof(filename_size)); filename_size = ntohl(filename_size); if (numbytes < sizeof(filename_size)) { printf("Protocol error, exiting.\n"); exit(1); } numbytes = recv_full(new_fd, filename, filename_size); filename[filename_size] = '\0'; if (numbytes < filename_size) { printf("Protocol error, exiting.\n"); exit(1); } if (file_exists(filename)) { printf("%s already exists. Overwrite? Y/n: ", filename); scanf("%c", &overwrite); if (overwrite == 'n') { close(new_fd); close(sockfd); exit(0); } } ft = fopen (filename, "wb"); if (ft == NULL) { perror("Cannon open file"); exit(1); } total = 0; while((numbytes = recv(new_fd, buf, MAXBUFLEN, 0)) > 0) { total += numbytes; printf("\rReceive: %zu", total); fwrite(&buf, 1, numbytes, ft); } printf("\nFile received: %s\n", filename); fclose(ft); close(new_fd); close(sockfd); }
// Define main() function for stage 1 of the communication. int main(int argc, char *argv[]) { int sockfd, new_fd; // Listen on sock_fd, new connection on new_fd. struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // Client's address information. socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; // Variable to store the string representation of the client's IP address. int rv; char buf[10000]; int numbytes; int n_port = atoi(argv[1]); if ((n_port < 1024) || (n_port > 65535)) { fprintf(stderr, "n_port must be between 1024 and 65535."); return 1; } // Generate random port number for the stage 2 of the communication - transaction using UDP sockets. srand (time(NULL)); int r_port = (rand() % 64512) + 1024; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP // Get the address info of the client. if ((rv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo() error: %s.", gai_strerror(rv)); return 1; } // Loop through all the results and bind to the first client. for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("socket() error."); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt() error."); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("bind() error."); continue; } break; } // Free the address info variables retrieved. freeaddrinfo(servinfo); if (p == NULL) { fprintf(stderr, "Server failed to bind."); exit(1); } if (listen(sockfd, 10) == -1) { perror("listen() error."); exit(1); } sa.sa_handler = sigchld_handler; // Reap all dead processes. sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction() error."); exit(1); } while(1) { // Main loop. sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); // Accept connection from the client. if (new_fd == -1) { perror("accept() error."); continue; } // Store the readable IP address of the client in variable s. inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof s); while(1) { // Connection error. if ((numbytes = recv(new_fd, buf, sizeof(buf), 0)) == -1) { perror("recv() error."); exit(1); } // Client connection closed. else if (numbytes == 0) { printf("Connection closed.\n"); // Server still listening to other connections break; } // Connection success. printf("\nNegotiation detected. Selected random port %d\n\n", r_port); // Send r_port to the client. if ((send(new_fd, &r_port, sizeof(int), 0)) == -1) { fprintf(stderr, "Sending r_port failed.\n"); } close(new_fd); // Close the TCP connection with the client. break; } // Negotiation phase (stage 1) complete. Move to UDP transaction. file_transfer(r_port); break; } return 0; // Return from the function. }
int main(int argc, char *argv[]) { int listen_sock_fd, client_newsock_fd, rtrv, bytes, b, s; int on = 1; struct addrinfo hints, *servinfo, *p; struct sockaddr_storage local_addr; socklen_t sin_size; char sck[INET6_ADDRSTRLEN]; char buffer[MAXBUFSIZE]; // Receive buffer for filename sent by client char buf[MAXBUFSIZE]; // Buffer for reading/writing data (bytes transferred) through socket if (argc != 2) { fprintf(stderr,"usage: server PORTNO \n"); exit(EXIT_FAILURE); } memset(&hints, 0, sizeof(hints)); //Replaces bzero() as a zero reset on struct parameters hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP hints.ai_protocol = 0; if ((rtrv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rtrv)); return(1); } // loop through all the results and bind to the first socket one can get (removing this loop produces a segmentation fault) for(p = servinfo; p != NULL; p = p->ai_next) { listen_sock_fd = socket(p->ai_family, p->ai_socktype,p->ai_protocol); if (listen_sock_fd == -1) { perror("server: socket"); continue; } else { printf("{SERVER}: Procured Socket Descriptor Successfully.\n"); } s = setsockopt(listen_sock_fd, SOL_SOCKET, SO_REUSEADDR, (char* ) &on, sizeof(on)); if (s == -1) { perror("setsockopt"); exit(EXIT_FAILURE); } else { printf("{SERVER}: Reused IP address Successfully\n"); } b = bind(listen_sock_fd, p->ai_addr, p->ai_addrlen); if (b == -1) { close(listen_sock_fd); perror("server: bind ERROR"); continue; } else { printf("{SERVER}: Binded to TCP port on localhost successfully.\n"); } break; } freeaddrinfo(servinfo); // all done with this structure if (p == NULL) { fprintf(stderr, "{SERVER}: could not bind\n"); exit(EXIT_FAILURE); } if (listen(listen_sock_fd, INQUEUE) == -1) { perror("listen failed"); exit(EXIT_FAILURE); } printf("{SERVER}: connections in queue...\n"); while(1) { // primary accept() loop sin_size = sizeof(local_addr); client_newsock_fd = accept(listen_sock_fd, (struct sockaddr *)&local_addr, &sin_size); if (client_newsock_fd == -1) { perror("accept"); continue; } else { printf("{SERVER}: Connection acccepted successfully\n"); } //Convert binary version of IP address to text. inet_ntop(local_addr.ss_family, get_in_addr((struct sockaddr *)&local_addr),sck, sizeof(sck)); printf("{SERVER}: got connection from %s\n", sck); /* Receive filename <input> from client */ recv(client_newsock_fd, buffer, MAXBUFSIZE, 0); printf("%s\n", buffer); /* Open the received input file from client */ FILE *fp = fopen(buffer, "wb"); if(fp == NULL) { printf("File %s cannot be opened on server\n", buffer); } else { printf("Reading file from buffer %s\n", buffer); memset(buf, 0, sizeof MAXBUFSIZE); bytes = 0; while ((bytes = recv(client_newsock_fd, buf, MAXDIVSIZE, 0))) { if(bytes < 0) { error("Receive error!\n"); } else { int write_div = fwrite(buf, sizeof(char), bytes, fp); // write data in chunks of 5 bytes printf("File Block Write Length is %d\n", write_div); } memset(buf, 0, sizeof buf); } fclose(fp); printf("Write file finished.\n"); } /*close connection*/ close(client_newsock_fd); } /* close socket */ close(listen_sock_fd); }