0

I am trying Socket programming using code blocks.

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <ws2tcpip.h>

int main()
{
    int sock;

    sock = socket(AF_INET6, SOCK_STREAM, 0);
    if(sock == -1)
    {
        printf("\n Socket not created %d\n", sock);
    }

    return 0;
}

The line to create socket gives me -1. What am I missing any help?

user1411601
  • 23
  • 2
  • 8
  • 1
    as a general suggestion, use `perror` because it will also give you the appropriate error message – tay10r Jun 17 '13 at 05:29
  • 1
    What's that constant `0` for the protocol? Shouldn't it be one of the `IPPROTO_` constants? –  Jun 17 '13 at 05:29
  • `IPPROTO_TCP`, for instance – tay10r Jun 17 '13 at 05:32
  • [IPv6 Socket Program Problem](http://stackoverflow.com/questions/5906736/ipv6-socket-program-problem) – Grijesh Chauhan Jun 17 '13 at 05:34
  • "Normally only a single protocol exists to support a particular socket type within a given protocol family, in which case protocol can be specified as 0." Not sure if win32 holds the same opinion, though. – hobbs Jun 17 '13 at 05:36
  • 2
    Q. What does 'using code blocks' have to do with it? A. Nothing. – user207421 Jun 17 '13 at 05:36
  • @EJP [Xcode tag.](http://stackoverflow.com/questions/tagged/xcode) - Some people can't even imagine iOS development without Xcode, and they want to "integrate Facebook into Xcode", "pop up a window in Xcode", and "learn Xcode programming". No matter I've been writing iOS apps on Linux (with `nano` and `make`) since 2010... –  Jun 17 '13 at 05:41
  • @H2CO3 I don't see anything even slightly Xcode-ish about this code, or anything even slightly out of the usual. – user207421 Jun 17 '13 at 07:16
  • @EJP I didn't say this code was Xcode-ish. I was just citing this as a similarity. –  Jun 17 '13 at 07:44

1 Answers1

4

You need to call WSAStartup function to initiate use of the Winsock DLL by a process.

Also, call WSACleanUp function at the end.

From the link WSAStartup:

The WSAStartup function must be the first Windows Sockets function called by an application or DLL. It allows an application or DLL to specify the version of Windows Sockets required and retrieve details of the specific Windows Sockets implementation. The application or DLL can only issue further Windows Sockets functions after successfully calling WSAStartup.

A good example is also given in the above link.

Also:

An application must call the WSACleanup function for every successful time the WSAStartup function is called. This means, for example, that if an application calls WSAStartup three times, it must call WSACleanup three times. The first two calls to WSACleanup do nothing except decrement an internal counter; the final WSACleanup call for the task does all necessary resource deallocation for the task.

raj raj
  • 1,932
  • 1
  • 14
  • 15