I am trying to write a basic socket application that will accept a string from a client and do some work on data structures I have in memory. I am trying to make use of C++11 because I'd like to have language support for multithreading and I've found an odd problem. I have code that creates a listen socket on port 1234, and accepts one connection, prints out a dummy string and closes it. If I compile it with:
g++ -o socket_test socket_test.cpp
it works perfectly, but if I compile it with:
g++ -std=c++11 -o socket_test socket_test.cpp
it compiles and runs fine, but if I try to connect to the port, it bounces back with connection refused. Test code is here:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
using namespace std;
int main()
{
cout << "Hello world, I'm going to open a socket on port 1234 now!" << endl;
int m_socket = 0;
int m_client = 0;
int port = 1234;
sockaddr_in serv_addr, client_addr;
socklen_t client_len;
m_socket = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(port);
bind(m_socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
cout << "Listen returns: " << listen(m_socket, SOMAXCONN) << endl;
m_client = accept(m_socket, (struct sockaddr *)&client_addr, &client_len);
write(m_client, "Numa numa\n", 10);
close(m_client);
close(m_socket);
return 0;
}
My build environment is OSX 10.9.2, using g++ as follows:
battra:socket_test matt$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr
--with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/
MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/usr/include/c++/4.2.1
Apple LLVM version 5.1 (clang-503.0.38) (based on LLVM 3.4svn)
Target: x86_64-apple-darwin13.2.0
Thread model: posix
battra:socket_test matt$