1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
//server
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <iostream.h>
#include <string.h>
#include <istream.h>
#include <string.h>
using namespace std;
int main()
{
struct sockaddr_storage their_addr;
socklen_t addr_size;
struct addrinfo hints, *res;
int sockfd, new_fd, con, die, sock, err, recv_bytes;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
getaddrinfo(NULL, "3490", &hints, &res);
// make a socket:
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(sockfd < 0)
{cout << "Error on socket level\n";
return -1;
}
bind(sockfd, res->ai_addr, res->ai_addrlen);
while(1)
{
listen(sockfd, 10);
addr_size = sizeof their_addr;
new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &addr_size);
if(new_fd == -1)
{
cout << "error accepting connection";
continue;
}
cout << new_fd;
char buf[256];
int len;
recv_bytes = recv( new_fd, buf, len, 0);
if(recv_bytes < len) {cout << "error recieving data, less bytes recieved than sent";}
cout << buf;
}
die = shutdown(sockfd,2);
if(die < 0)
{cout << "Failed to shutdown\n";
return -1;
}
if(die == 0){cout << "Success!\n";}
return new_fd;
}
|