Link to home
Start Free TrialLog in
Avatar of level9wizard
level9wizardFlag for Canada

asked on

How can I send a packet with c++?

How can I create and send a UDP and/or TCP packet (stream) from c++? I'm compiling using MingW in Code::Blocks IDE, on Windows Vista 64-bit.
SOLUTION
Avatar of Arabia_vn
Arabia_vn
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
In samples of wxWidget you have a wxSocketClient and wxSocketServer, as I see you want to send data to check the Client one.
http://docs.wxwidgets.org/stable/wx_wxsocketclient.html#wxsocketclient

Documentation is here and you already have the sample. Review it and it uses WxSocket, it's cross platform, so don't worry.
Avatar of level9wizard

ASKER

Thanks for the posts everyone. Please allow some time for me to look through and reply.
To the above, can you please provide a working example for Windows (as I mentioned in my original question). These example mentioned above either are intended for linux (i.e. using netdb.h where it should be winsock2.h based on https://www.experts-exchange.com/questions/20652112/fatal-error-C1083-Cannot-open-include-file-'netdb-h'-No-such-file-or-directory.html ) or are not complete examples.

Please paste a full working example, thanks!
SOLUTION
Avatar of Infinity08
Infinity08
Flag of Belgium image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
>>>> For Windows, you just have to take into account the note for Windows programmers
Unfortunately the main intention of those remarks seems to have the purpose to show how witty the author can be .... what makes the most advises unusable or wrong.

The WSAStartup/WSACleanup calls are ok though you shouldn't use Winsock1.1 but Winsock 2.2 which is the highest (current) version supported. That implies to including winsock2.h (instead of winsock.h) and using the library ws2_32.lib which corresponds to these versions.

A fork duplicates the current process (with all current threads). If used in UNIX programs its purpose mostly is to get an exact copy of the current process to process multiple tasks parallel. I personally doubt that socket processing really needs those - heavyweight - forks but even if you try to port that feature to Windows you should consider that CreateProcess (don't be afraid of the numerous arguments as only a few must be supplied) creates a new process rather than is copying the existing one at the current status. So you would need to pass the information needed from starting process somehow, e. g. by commandline arguments or by P2P communication what IMO both make things more complex than needed.

The alternative for forks and duplicate processes are threads. If you give each thread its own resources and don't access shared resources you have most benefits of a fork and the main difference left is that you need to synchronize thread termination from the main thread cause ending the main thread would terminate all threads as well. You best do that by establishing some kind of messaging between threads where a final stop message would terminate all threads and finally the whole process.

If you neither want to have multi-threading nor forks you can achieve that by making the sockets non-blocking.

       // switch socket to non-blocking
       long on = 1;   // 0 would set the socket to blocking
       ioctlsocket(sock, FIONBIO, &on);

After doing that for a socket sock,  nearly all calls to recv, or recvfrom were returning socket error -1 and additional status WSAEWOULDBLOCK (retrieved by WSAGetLastError) and you would need to implement some kind of polling in order to not using all CPU (though that might not matter on a multi-core processor).

A better way normally is to call select with timeout what indicates that you can read without blocking when the select on the read socket returns TRUE.  

For an UDP socket you have no connection. For sending a buffer to an UDP server you don't need much more than a socket, a well-filled struct socketaddr and a sendto call.



[Arabia_vn]>>Try some tutorial here http://beej.us/guide/bgnet/output/html/multipage/index.html
[Infinity08] >> Beej's guide to network programming (see http:#26116890) contains complete and clear explanations... you just have to take into account the note for Windows programmers
[itsmeandnobodyelse ] >> Unfortunately the main intention of those remarks seems to have the purpose to show how witty the author can be

I agree with itsmeandnobodyelse, this guide doesn't seem to be a technical document, it's a bit too wordy and biased. Also, the code is broken up over the tutorial and I couldn't find one bundled download with complete example. Even more important, the note to windows coders doesn't explain what to do about all the linux header files. I did however find the answer to that question myself at this site [http://tangentsoft.net/wskfaq/articles/bsd-compatibility.html] stating "For Winsock, you dont need any of these. Instead, you just need to include winsock.h".

I'm still really hoping for a complete, compilable example here that will run as per my specs mentioned in the original question. Maybe I'll just have to award some points and make a new question based on this thread that clearly states that I need a fully working example.
Have you seen my comments and examples for wxWidget?
>> this guide doesn't seem to be a technical document, it's a bit too wordy and biased.

It is one of the best guides you'll find out there :)
And although it is primarily written for Unix systems (because that's where sockets come from), the necessary notes to make things work on Windows have been added later too. I've never had a problem with that guide to make things work on any platform. You might not trust my recommendation, but I still give it to you :)
Btw, it's wordy, because it clearly explains the how and why of everything - you can always skip the wordy bits ;)

>> Also, the code is broken up over the tutorial and I couldn't find one bundled download with complete example.

Maybe you missed the complete examples in section 6 ?

        http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#clientserver


>> Even more important, the note to windows coders doesn't explain what to do about all the linux header files.

It said so in the middle of the note for Windows programmers :

        "first, ignore pretty much all of the system header files I mention in here. All you need to include is:

                #include <winsock.h>"

That's pretty clear, isn't it ?

Note that there's also a link at the end of that section to this WinSOCK FAQ :

        http://tangentsoft.net/wskfaq/

(the same btw where you found your information eventually)
[CSecurity]>>Have you seen my comments and examples for wxWidget?
I have, but was very unfamiliar with this. Your links lead me to learn more about it at wxwidgets.org where I found out that this seems to be a very heavy library for what I'm trying to do. If you could post a working example as per my original post that would be fantastic.

[Infinity08]>>It said so in the middle of the note for Windows programmers ... That's pretty clear, isn't it ?
For me no, it wasn't. I could see that #include <stdio.h> and #include <stdlib.h> are obviously going to be needed even for Windows programmers - so saying, "pretty much all of the system header files I mention in here." is about as unclear to someone trying to learn this stuff as it can be. I would have much rather had a full working example. Moreover, I tried some of the examples, starting with the one on page http://beej.us/guide/bgnet/output/html/multipage/syscalls.html (http://beej.us/guide/bgnet/examples/showip.c) and was getting INET6_ADDRSTRLEN undeclared. This is the kind of thing that makes it hard to learn for me, and the same reason I was hoping for a fully compilable example posted here. I went ahead and defined this myself, but got more errors (don't have the exact message where I am at currently) but was to the tune of "ai_family is not a member of hints struct" suggesting this is not defined in Windows.h ? Perhaps this is something to do with WSAStartup()?


In some ways I actually really do like the way that Beej's guide 'softens' such a technical learning environment. However, I'm still having a really hard time finding a working example where I can form and send a tcp and/or udp packet.

I really do appreciate the replies guys. Looks like I'm going to have to award points and open the new question/
>> I could see that #include <stdio.h> and #include <stdlib.h> are obviously going to be needed even for Windows programmers

Those are standard C headers, and have nothing to do with socket programming.


>> is about as unclear to someone trying to learn this stuff as it can be

If you're learning C/C++ at the same time as you're learning socket programming, I can see what caused the confusion. May I suggest learning C/C++ first, and then tackling something more complex, like socket programming ? It would make things like this a lot easier for you :)


>> This is the kind of thing that makes it hard to learn for me

Nobody said that (socket) programming was easy ;) You will have errors, and other problems - that's a given. Most of those however are dealt with in Beej's guide, or can be found elsewhere. Alternatively, you can ask here if you're stuck on a problem.


>> but was to the tune of "ai_family is not a member of hints struct" suggesting this is not defined in Windows.h ?

ai_family is a member of struct addrinfo (both on Unix and Windows systems). 'hints' should have been defined something like :

        struct addrinfo hints;

and then you can access hints.ai_family and the other members of the struct.

Could you show the code you have right now ? We can help you better that way.


>> Looks like I'm going to have to award points and open the new question/

No need for that. We're here to assist you until your question has been fully answered :)
>> Those are standard C headers, and have nothing to do with socket programming.
That's my point.
>> Could you show the code you have right now ? We can help you better that way.

Kind of ironic cause that's what I'm asking to be pasted here - hahaha! Anyways I do have something to show and that is:
http://beej.us/guide/bgnet/examples/showip.c (with of course the windows.h and define mods I've already mentioned)

I'm not at the PC with this production so I'll paste the errors and full code whence I arrive.
>> Kind of ironic cause that's what I'm asking to be pasted here -

Heh. I thought you tried to make it work following the guide, and got some errors along the way. So I was asking to post how far you got and where you were stuck.


>> http://beej.us/guide/bgnet/examples/showip.c

All you should have to do is replace the headers, and add the WSAStartup and WSACleanup calls, then make sure to link to the winsock library, and that should do it.

Note that there might be slight variations depending on which version of winsock you use.
This is still a stretch from what I've asked for in my original question, but to be cooperative I'm trying to get any one of of Beej's examples to run in the Windows environment I've outlined. So far i'm trying to compile the showip.c already mentioned and so I've attached the source i'm compiling and the errors/warnings I'm getting so far. I tried both compiling as c and c++ console.

So far the only things I've changed from the Beej's guide is the headers, and added the WSA startup code.
/*
** showip.c -- show IP addresses for a host given on the command line
*/

#include <stdio.h>
#include <string.h>
#include <windows.h>

int main(int argc, char *argv[])
{

    WSADATA wsaData;   // if this doesn't work
    //WSAData wsaData; // then try this instead

    // MAKEWORD(1,1) for Winsock 1.1, MAKEWORD(2,0) for Winsock 2.0:

    if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0) {
        fprintf(stderr, "WSAStartup failed.\n");
        exit(1);
    }

	struct addrinfo hints, *res, *p;
	int status;
	char ipstr[INET6_ADDRSTRLEN];

	if (argc != 2) {
	    fprintf(stderr,"usage: showip hostname\n");
	    return 1;
	}

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
	hints.ai_socktype = SOCK_STREAM;

	if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
		return 2;
	}

	printf("IP addresses for %s:\n\n", argv[1]);

	for(p = res;p != NULL; p = p->ai_next) {
		void *addr;
		char *ipver;

		// get the pointer to the address itself,
		// different fields in IPv4 and IPv6:
		if (p->ai_family == AF_INET) { // IPv4
			struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
			addr = &(ipv4->sin_addr);
			ipver = "IPv4";
		} else { // IPv6
			struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
			addr = &(ipv6->sin6_addr);
			ipver = "IPv6";
		}

		// convert the IP to a string and print it:
		inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
		printf("  %s: %s\n", ipver, ipstr);
	}

	freeaddrinfo(res); // free the linked list

	return 0;
}



----------------------------------------------
--------------------------------------- ERRORS 
----------------------------------------------

C:\Code\SocketSandbox\main.cpp||In function `int main(int, char**)':|
C:\Code\SocketSandbox\main.cpp|22|error: aggregate `addrinfo hints' has incomplete type and cannot be defined|
C:\Code\SocketSandbox\main.cpp|24|error: `INET6_ADDRSTRLEN' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|35|error: `getaddrinfo' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|36|error: `gai_strerror' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|36|warning: unused variable 'gai_strerror'|
C:\Code\SocketSandbox\main.cpp|35|warning: unused variable 'getaddrinfo'|
C:\Code\SocketSandbox\main.cpp|42|error: invalid use of undefined type `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|22|error: forward declaration of `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|48|error: invalid use of undefined type `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|22|error: forward declaration of `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|49|error: invalid use of undefined type `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|22|error: forward declaration of `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|53|error: invalid use of undefined type `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|22|error: forward declaration of `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|54|error: invalid use of undefined type `struct sockaddr_in6'|
C:\Code\SocketSandbox\main.cpp|53|error: forward declaration of `struct sockaddr_in6'|
C:\Code\SocketSandbox\main.cpp|59|error: invalid use of undefined type `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|22|error: forward declaration of `struct addrinfo'|
C:\Code\SocketSandbox\main.cpp|59|error: `ipstr' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|59|error: `inet_ntop' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|59|warning: unused variable 'inet_ntop'|
C:\Code\SocketSandbox\main.cpp|63|error: `freeaddrinfo' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|24|warning: unused variable 'INET6_ADDRSTRLEN'|
C:\Code\SocketSandbox\main.cpp|63|warning: unused variable 'freeaddrinfo'|
||=== Build finished: 19 errors, 5 warnings ===|

Open in new window

As mentioned in the Windows note, all you need to do to make that code work is add the proper headers :

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

(you don't need <windows.h>). And make sure you link against the WS2_32.lib library.
[Infinity08]>>(you don't need <windows.h>). And make sure you link against the WS2_32.lib library.

Hmm that's strange - I actually don't know why I have that written there. I think i might have pasted that from the wrong file I was working on (and then of course the errors as well). The correct file was using <winsock.h> but not <ws2tcpip.h>. Beej's guide did not mention this file, should I still use it?

Thanks for your continued effort in helping me out with this! I'll have an update shortly.
>> Beej's guide did not mention this file, should I still use it?

Yes. Microsoft has decided to move certain functionality to a different header file. Since your code is using some of that functionality, you need the include.

That part of the Windows note in Beej's guide would indeed benefit from an addendum ... But afaik the note was written before these new headers even existed.


>> I think i might have pasted that from the wrong file I was working on (and then of course the errors as well).

Most of the errors/warnings might have been due to including <windows.h> BEFORE <winsock2.h> and <ws2tcpip.h>. The order is important here unfortunately, and you need to include <winsock2.h> and <ws2tcpip.h> before <windows.h> (if you need <windows.h> that is).
[level9wizard]>>> but was to the tune of "ai_family is not a member of hints struct" suggesting this is not defined in Windows.h ?
[Infinity08]>>>ai_family is a member of struct addrinfo (both on Unix and Windows systems). 'hints' should have been defined something like :
^
[Infinity08]>>Most of the errors/warnings might have been due to including <windows.h> BEFORE <winsock2.h> and <ws2tcpip.h>
I think for some reason I was working on something else at the time using windows.h, and included it and pasted my wrong working code/errors - my mistake sorry. As you can see above I even wrote it in the question for some reason hmm.. weird on me! haha!

Anyways, I've cleaned things up and attached my correct workings of the showip.c program and the errors when trying to compile (remember, my intention is to actually send a packet, not get showip.c working). Although, I very much appreciate the learning and your efforts. I often learn much quicker when I have a fully functioning example I can compile for myself. This lets me walk through the code knowing it's going to have all of the declarations; clicking on just about anything within code::blocks takes me to its declaration and/or implementation to learn more about it. As much as I am still ervy new to c++, it helps me tremendously, but will only work if it's 100% complete of course.

/*
** showip.c -- show IP addresses for a host given on the command line
*/

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

int main(int argc, char *argv[])
{

    WSADATA wsaData;   // if this doesn't work
    //WSAData wsaData; // then try this instead

    // MAKEWORD(1,1) for Winsock 1.1, MAKEWORD(2,0) for Winsock 2.0:

    if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0) {
        fprintf(stderr, "WSAStartup failed.\n");
        exit(1);
    }

	struct addrinfo hints, *res, *p;
	int status;
	char ipstr[INET6_ADDRSTRLEN];

	if (argc != 2) {
	    fprintf(stderr,"usage: showip hostname\n");
	    return 1;
	}

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC; // AF_INET or AF_INET6 to force version
	hints.ai_socktype = SOCK_STREAM;

	if ((status = getaddrinfo(argv[1], NULL, &hints, &res)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(status));
		return 2;
	}

	printf("IP addresses for %s:\n\n", argv[1]);

	for(p = res;p != NULL; p = p->ai_next) {
		void *addr;
		char *ipver;

		// get the pointer to the address itself,
		// different fields in IPv4 and IPv6:
		if (p->ai_family == AF_INET) { // IPv4
			struct sockaddr_in *ipv4 = (struct sockaddr_in *)p->ai_addr;
			addr = &(ipv4->sin_addr);
			ipver = "IPv4";
		} else { // IPv6
			struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
			addr = &(ipv6->sin6_addr);
			ipver = "IPv6";
		}

		// convert the IP to a string and print it:
		inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
		printf("  %s: %s\n", ipver, ipstr);
	}

	freeaddrinfo(res); // free the linked list

	return 0;
}

///////////////////////////////////// Errors \/



C:\Code\SocketSandbox\main.cpp||In function `int main(int, char**)':|
C:\Code\SocketSandbox\main.cpp|36|error: `getaddrinfo' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|36|warning: unused variable 'getaddrinfo'|
C:\Code\SocketSandbox\main.cpp|60|error: `inet_ntop' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|60|warning: unused variable 'inet_ntop'|
C:\Code\SocketSandbox\main.cpp|64|error: `freeaddrinfo' was not declared in this scope|
C:\Code\SocketSandbox\main.cpp|64|warning: unused variable 'freeaddrinfo'|
||=== Build finished: 3 errors, 3 warnings ===|

Open in new window

ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
[Infinity08] >> Are you using an old version of Windows ? Older than Windows XP more specifically ? That might explain it.
In my original question you'll see I've outlined my o/s (Windows Vista 64-bit.)

[Infinity08] >>On certain platforms, one could add this define before the includes :  #define _WIN32_WINNT 0x501
I actually commented that out from inside of ws2tcpip.h as per my findings here: http://www.daniweb.com/forums/thread169481.html (post #5). This error is now gone; however, there's still the matter of "C:\code_projects\SocketSandbox\main.cpp|60|error: `inet_ntop' was not declared in this scope|". It looks like this is using "p->ai_family, addr, ipstr" to convert to a readable IPv4 or IPv6 string - so it's not really that big of a deal, I'm sure I could recreate that if needed. I commented that out and it ran just fine (without of course showing the ip's since no inet_ntop") - it just was blank.

As a reminder, this example is far from my original effort. Therefore, I am going to close and award points. However, I am going to also create a new related question (based on this) and award points to whomever can find me a working example as per my original post.
>> In my original question you'll see I've outlined my o/s (Windows Vista 64-bit.)

Right. Then it might be related to Code::Blocks ... But I'm not sure.


>> I actually commented that out from inside of ws2tcpip.h

You should probably not modify the system header ws2tcpip.h ... Other things might break.


>> `inet_ntop' was not declared in this scope|".

Microsoft has not (yet) implemented that function. Take a look at this as an alternative maybe :

        http://msdn.microsoft.com/en-us/library/cc805843%28VS.85%29.aspx
[Infinity08]>>Microsoft has not (yet) implemented that function. Take a look at this as an alternative maybe : http://msdn.microsoft.com/en-us/library/cc805843%28VS.85%29.aspx

Thanks for taking the time to find that even after points are awarded! Check out my new thread here, really hoping to get a full working tcp/udp packet send example in Windows Vista :) Feel free to take a stab at it :)
https://www.experts-exchange.com/questions/25030550/How-can-I-send-a-packet-with-c-example-required.html
>> Thanks for taking the time to find that even after points are awarded!

Points are not what counts ... It's trying to help out that is the fun part ;)


>> packet send

Note that sending packets is a low-level operation, and is commonly handled by the OS. Socket programming is an abstraction on a higher level ... You won't send packets explicitly, but you will send data, and the underlying stack will decide how to put that data in packets.
>> Feel free to take a stab at it :)

I might later if I get some time on a Windows machine. It's just a matter of adjusting the headers and such.
>> Note that sending packets is a low-level operation, and is commonly handled by the OS. Socket programming is an abstraction on a higher level ... You won't send packets explicitly, but you will send data, and the underlying stack will decide how to put that data in packets.

Even though I'm new to this, I was already beginning to see that the discussion from others and even the guides (i.e. Beej's) don't provide a direct way to form the packet from these examples, but rather provide an interface to a socket. Even in my new post an example was provided that seems to only create a socket object, not direct access to the packet as you have just mentioned.

My whole intent behind this is that I want to (believe it or not legitimately) spoof certain packets. The reason is, I want to perform certain automated tasks or groups of tasks that otherwise need to occur manually from inside a given application (i.e computer video game). I have a number of practical uses for this that would make my life so much easier. Using a network traffic analyzer tool (Wireshark) I can see the contents being sent to and from my computer game and the server, such as messaging a friend, or joining a lobby. When a friend joins a game, it notifies me (and I can see those packets transferred). I'd like to then send certain packets that would otherwise take a series of tedious, human-performed actions, in only one shortcut or hotkey mapped inside my c++ app.
>> (i.e computer video game)

fyi, depending on the game, and how strict they are, this might be seen as cheating ;)

Now, if what you're trying to do stays at application level, you can still manage with normal socket programming. As soon as you dive below that level though, you'll need lower-level access.

You'd need to bypass the system's protocol stack, and manage everything yourself. Raw sockets can do that for you :

         http://msdn.microsoft.com/en-us/library/ms740548(VS.85).aspx