C++ Socket Error

All,

I have used sockets for a while and this UDP code. I don't understand why it doesn't work when being built and ran from windows (code orginally used in linux and cygwin).

I'm using MS Visual Studio 2008 Express, can someone tell me what I'm missing here. I'm not a windows programmer.

Error:
1
2
3
In function:  sendMsg()
Operational Failed:  sendMsg()
Error socket:  : No such file or directory


Includes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma comment(lib, "wsock32.lib")

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef WIN32
#include <unistd.h>
#include <sys/socket.h> 
#include <arpa/inet.h>  
#else
#include <winsock2.h>
//#include <windows.h>
//#include <winsock.h>
#endif 


Coding
1
2
3
4
5
6
7
8
9
10
11
12
13
14
   cout << "In function:  sendMsg()" << endl;
   struct sockaddr_in addr;
   //int fd, nbytes;
   int nbytes;
   SOCKET fd = INVALID_SOCKET;

   // create what looks like an ordinary UDP socket
   //if ((fd=socket(AF_INET,SOCK_DGRAM,0)) < 0)  == INVALID_SOCKET
   if ((fd=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) == INVALID_SOCKET )  
   {
      cout << "Operational Failed:  sendMsg()" << endl;
      perror("Error socket:  ");
      //exit(1);
   }

A couple of questions:

- Did you link against Ws2_32.lib? EDIT: This is the library for WinSock2.

- Did you initialize the COM with the WSAStartup() function? : http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213(v=vs.85).aspx

Last edited on
If you've ported from Unix, then you probably haven't initialised the socket library.

See WSAStartup().
http://msdn.microsoft.com/en-us/library/windows/desktop/ms742213%28v=vs.85%29.aspx

And please link as described above by Computergeek01.
Computergeek thank you. That did the trick.
Topic archived. No new replies allowed.