Created
August 4, 2014 16:02
-
-
Save sunny1304/624dc310b060c5010c9a to your computer and use it in GitHub Desktop.
simple server example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#define PORT 7890 | |
int main(int argc, char** argv) | |
{ | |
int sockfd, new_sockfd; | |
struct sockaddr_in host_addr, client_addr; | |
socklen_t sin_size; | |
int recv_length = 1, yes = 1; | |
char buff[1024]; | |
memset(&buff, '\0', 1024); | |
sockfd = socket(PF_INET, SOCK_STREAM, 0); | |
if (sockfd == -1) perror("in socket\n"); | |
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) perror("setting socket option SO_REUSEADDR\n"); | |
host_addr.sin_family = AF_INET; | |
host_addr.sin_port = htons(PORT); | |
host_addr.sin_addr.s_addr = 0; | |
memset(&(host_addr.sin_zero), '\0', 8); | |
if (bind(sockfd, (struct sockaddr*)&host_addr, sizeof(struct sockaddr)) == -1) perror("binding to socket\n"); | |
if (listen(sockfd, 5) == -1) perror("listening on socket\n"); | |
while(1) | |
{ | |
sin_size = sizeof(struct sockaddr_in); | |
new_sockfd = accept(sockfd, (struct sockaddr*)&client_addr, &sin_size); | |
if (new_sockfd == -1) perror("accepting connection\n"); | |
printf("server got connection from %s prot %d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); | |
send(new_sockfd,"Hello world\n", 11, 0); | |
recv_length = recv(new_sockfd, &buff, 1024, 0); | |
while(recv_length > 0) | |
{ | |
printf("received %d bytes --> %s\n", recv_length, (char*)&buff); | |
memset(&buff, '\0', 1024); | |
recv_length = recv(new_sockfd, &buff, 1024, 0); | |
} | |
close(new_sockfd); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment