Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Standard C++ headers
- #include <iostream>
- #include <cstring>
- #include <cstdlib>
- #include <string>
- // Socket headers
- #include <sys/socket.h>
- #include <netinet/ip.h>
- #include <arpa/inet.h>
- // UNIX system headers
- #include <errno.h>
- using namespace std;
- const int SERVER_PORT=0;
- const int MAX_PENDING=5;
- const int MAX_LINE=256;
- void handle_error(int eno, char const *msg)
- {
- if(eno == 0)
- cerr << msg << endl;
- else
- cerr << msg << ": "<< strerror(eno) << endl;
- exit(errno);
- }
- int main(int argc, char *argv[])
- {
- int nread;
- socklen_t len;
- sockaddr_in sin;
- sockaddr *sin_p = (sockaddr *)&sin;
- sin.sin_family = AF_INET; // IP version 4
- sin.sin_port = htons(SERVER_PORT);
- sin.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all IP addresses
- int rstat;
- cout << ntohs(sin.sin_port) << endl;
- // Create socket
- int s = socket(AF_INET, SOCK_STREAM, 0);
- if(s == -1)
- handle_error(errno, "simplex_server - socket");
- // Bind socket to local address
- rstat = bind(s, sin_p, sizeof(sin));
- if(rstat == -1)
- handle_error(errno, "simplex_server - bind");
- rstat = listen(s, MAX_PENDING);
- if(rstat == -1)
- handle_error(errno, "simplex_server - listen");
- // Allocate a memory buffer for received messages
- char *buf = new char[MAX_LINE];
- // Wait for connections
- while(true) {
- // Upon return the sin structure will contain the address of the
- // connecting socket. Note that a new socket is returned.
- len = sizeof(sin);
- int new_s = accept(s, sin_p, &len);
- if(new_s == -1)
- handle_error(errno, "simplex_server - accept");
- // Display IP addr and Port
- len = sizeof(sin);
- rstat = getpeername(new_s, sin_p, &len);
- if (rstat == -1)
- handle_error(errno, "simplex_server - address and port");
- // h_addr contains the memory address of the IP address (?!?)
- // The IP addresses are in network byte order
- char *dst = new char[INET_ADDRSTRLEN];
- const char *rmem = inet_ntop(AF_INET, &sin.sin_addr, dst, INET_ADDRSTRLEN);
- if(rmem == NULL)
- handle_error(errno, "simplex_client - inet_ntop");
- cout << "Client IP Address: " << dst << endl;
- cout << "Client IP Port: " << ntohs(sin.sin_port) << endl;
- // Receive and print messages as long as client is connected.
- while(true) {
- nread = recv(new_s, buf, MAX_LINE, 0);
- if(nread == -1)
- handle_error(0, "simplex_server - recv");
- if (nread == 0) break; // client has disconnected
- cout << buf << flush;
- }
- close(new_s);
- }
- close(s);
- delete [] buf;
- return 0;
- }
Add Comment
Please, Sign In to add comment