Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <arpa/inet.h>
- #include <sys/socket.h>
- #include <sys/types.h>
- #include <netdb.h>
- #include <stdlib.h>
- #include <string.h>
- #include <unistd.h>
- #include <string>
- #include <netinet/in.h>
- using namespace std;
- int main()
- {
- sockaddr_in serverData;
- //Create socket
- int sockfd = socket(AF_INET, SOCK_STREAM, 0);
- if(sockfd == -1)
- {
- cout << "Can't create a socket" << endl;
- return -1;
- }
- serverData.sin_family = AF_INET;
- serverData.sin_port = htonl(8080);
- inet_pton(AF_INET, "0.0.0.0", &serverData.sin_addr);
- //Bind socket
- int bindRes = bind(sockfd, (sockaddr *)&serverData, sizeof(serverData));
- if(bindRes == -1)
- {
- cout << "Can't bind" << endl;
- return -2;
- }
- //Listen
- int listenRes = listen(sockfd, 3);
- if(listenRes == -1)
- {
- cout << "In listening" << endl;
- return -3;
- }
- sockaddr_in client;
- //Accept the only connection and close the port
- cout << "Waiting for connection " << endl;
- int clientSock = accept(sockfd, (sockaddr*) &client, (socklen_t*) sizeof(client));
- if(clientSock < 0)
- {
- cout << "Can't accept connection " << endl;
- exit(93);
- }
- close(sockfd);
- char clientName[NI_MAXHOST];
- char clientPort[NI_MAXSERV];
- //Fill buffer with clients host name and port number
- cout << "Here" << endl;
- getnameinfo((sockaddr*) &client, (socklen_t) sizeof(client), clientName, NI_MAXHOST, clientPort, NI_MAXSERV, 0);
- cout << "Client name is: " << (string)clientName << endl;
- cout << "Client port is: " << (string)clientPort << endl;
- while(1)
- {
- char buff[4096];
- //Receive data that was send by client
- int bytesRecv = recv(clientSock, buff, 4096, 0);
- if(bytesRecv == -1)
- {
- break;
- }
- if(bytesRecv == 0)
- {
- cout << "Client disconnected" << endl;
- break;
- }
- else
- {
- //Output that data and send it back
- cout << string(buff, 0, bytesRecv) << endl;
- send(clientSock, buff, bytesRecv + 1, 0);
- }
- }
- close(clientSock);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement