Re: can't get server socket working
On 29/10/2013 16:31, cerr wrote:
Hi,
I'm trying to get a server socket working but for some reason this doesn't allow any connections on 127.0.0.1:1234. What might be wrong here? No errors are being reported:
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <stdio.h>
#define BUF_SIZE 500
using namespace std;
int getserversocket(int port);
int main (void)
{
socklen_t peer_addr_len;
ssize_t nread;
int sockhandle, s;
struct sockaddr_storage peer_addr;
char buf[BUF_SIZE];
cout << "MyServer 1.0" << endl;
if (sockhandle = getserversocket(1234) >= 0){
cout << "Socket created!" << endl;
} else {
cout << "Could not bind" << endl;
}
while(sockhandle >= 0) {
peer_addr_len = sizeof(struct sockaddr_storage);
nread = recvfrom(sockhandle, buf, BUF_SIZE, 0,
(struct sockaddr *) &peer_addr, &peer_addr_len);
if (nread == -1)
continue; /* Ignore failed request */
char host[NI_MAXHOST], service[NI_MAXSERV];
s = getnameinfo((struct sockaddr *) &peer_addr,
peer_addr_len, host, NI_MAXHOST,
service, NI_MAXSERV, NI_NUMERICSERV);
if (s == 0)
cout << "Received "<< (long)nread << "bytes from " << host << ":" << service << endl;
else
fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
if (sendto(sockhandle, buf, nread, 0,
(struct sockaddr *) &peer_addr,
peer_addr_len) != nread)
cout << "Error sending response" << endl;
}
}
int getserversocket(int port)
{
struct addrinfo hints;
struct addrinfo *result, *rp;
int addrinfo, sock;
char port_chr[5];
sprintf(port_chr,"%d",port);
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */
hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
hints.ai_protocol = 0; /* Any protocol */
hints.ai_canonname = NULL;
hints.ai_addr = NULL;
hints.ai_next = NULL;
addrinfo = getaddrinfo(NULL, port_chr, &hints, &result);
if (addrinfo != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(addrinfo));
exit(EXIT_FAILURE);
}
for (rp = result; rp != NULL; rp = rp->ai_next) {
sock = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (sock == -1)
continue;
if (bind(sock, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
close(sock);
}
freeaddrinfo(result); /* No longer needed */
if (rp == NULL) { /* No address succeeded */
return -1;
}
else
return sock;
}
Any assistance would be appreciated, Thank you!
Step 1) Stop using old C techniques and use boost.asio instead.
Step 2) A lot easier after step 1.