simple tcp echo program not working when SDL included? - c++

I have this weird problem where whenever I #include "SDL/SDL.h", my windows socket program doesn't execute. It compiles but it doesn't do anything when run. When I remove the #include "SDL/SDL.h" header, compile and run, it starts working again??.
I'm trying to make both SDL and my original socket program work but I don't understand whats wrong this.
//#include "SDL/SDL.h"
#define _WIN32_WINNT 0x501
#include <iostream>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string.h>
#include <ws2tcpip.h>
#define MAXLEN 80
using namespace std;
const int winsockVersion = 2;
int main( int argc, char* args[] ) {
WSADATA wsadata;
if ( (WSAStartup(MAKEWORD(2,0),&wsadata)) == 0){
cout<<"-[ WSAStartup Initialized. ]" << endl;
char PORT[MAXLEN];
char SERVER[MAXLEN];
cout <<"Server: ";
cin>>SERVER;
cout <<"Port: ";
cin>>PORT;
struct addrinfo hints, *res;
int sockfd;
memset(&hints,0,sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(SERVER,PORT,&hints,&res) != 0){
cout<<"-Getaddrinfo unsuccessful." << endl;
}
if ( (sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol)) == -1 ){
cout<<"-Unable to create socket." << endl;
}
if ( (connect(sockfd,res->ai_addr,res->ai_addrlen)) != -1 ){
cout<<"-[ Connection Established. ]" << endl;
}
cout<<"-[ Client connecting to: ]" << res->ai_addr << endl;
while(true){
string text_buff;
cout<<"Send: ";
getline(cin,text_buff);
if( (send(sockfd,text_buff.c_str(),text_buff.length()+1,0)) != -1 ){
cout<<"-----------------------------------> Data sent!." << endl;
}
if ( text_buff == "quit" ){
break;
}
}
}else{
cout<<"-WSAStartup Initialization failed." << endl;
if(WSACleanup()!=0){
cout<<"-WSACleanup Successful." << endl;
}else{
cout<<"-WSACleanup Failed." << endl;
}
}
return 0;
}
compiling with
g++ -o draft.exe draft.cpp -I"C:\compilers and libs\Libs\SDL\SDL devep\SDL-1.2.15\include" -L"C:\compilers and libs\Libs\SDL\SDL devep\SDL-1.2.15\lib" -lmingw32 -lSDLmain -lSDL -lws2_32

As far as I know SDL rewrites the main function with some silly #define main trick, it intercepts program main like that.
Therefore, main might not be getting called at all.
If I remember right, your main function (arguments) should be exactly int main(int argc, char *argv[]).

Related

Segmentation fault with client C++ program

I am having some difficulty with finding out how to correct the segmentation fault.
client.cpp
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <arpa/inet.h>
using namespace std;
int call_socket(char *hostname, unsigned short portnum)
{
struct sockaddr_in sa;
struct hostent *hp;
int a;
int s;
if ((hp = gethostbyname(hostname)) == NULL)
{
errno = ECONNREFUSED;
return(-1);
}
memset(&sa, 0, sizeof(sa));
memcpy((char*) &sa.sin_addr, hp->h_addr, hp->h_length);
sa.sin_family = hp->h_addrtype;
sa.sin_port = htons((u_short)portnum);
if ((s=socket(hp->h_addrtype, SOCK_STREAM, 0)) < 0)
{
return(-1);
}
if (connect(s, (struct sockaddr*)&sa, sizeof (sa)) < 0)
{
close(s);
return(-1);
}
return(s);
}
int main(int argc, char* argv[])
{
int n;
int s;
int b;
char username[256];
string hostname;
string usern;
string terminated = "Server Terminated";
string doesnotexist = "does not exist.";
hostname = "localhost";
char *hostn[hostname.size()+1];
strcpy(*hostn, hostname.c_str());
cout << "Enter a server port number: " << endl;
cin >> s;
while (s <2000 || s > 65535)
{
cout << "Server port number must be between 2000 and 65535. Please enter the server port number again." << endl;
cin >> s;
}
if ((b = call_socket(*hostn,s)) < 0)
{
perror("call Socket");
exit(1);
}
cout << "Enter a user name: " << endl;
cin >> usern;
strcpy(username, usern.c_str());
n = write(b, username, strlen(username));
if (n < 0)
{
cout << "Error writing to socket" << endl;
}
bzero(username, 256);
n = read(b,username,255);
if (n < 0)
{
cout << "Error reading from socket" << endl;
}
if (username == terminated)
{
printf("%s\n",username);
}
else if (username == doesnotexist)
{
cout << "The username: " << usern << ", ";
printf("%s\n",username);
}
else
{
cout << "The public key for " << usern << " is: ";
printf("%s\n",username);
}
close(b);
return 0;
}
I tried valgrind and got: Conditional jump or move depends on uninitialised value(s), Use of uninitialised value of size 8, Invalid write of size 8. As I am unexperienced with valgrind, I don't really know how to fix it.
Your problem is almost certainly here:
char *hostn[hostname.size()+1];
strcpy(*hostn, hostname.c_str());
This has several issues:
hostn is a variable-length-array, which is not a standard part of C++
hostn is an array of char*, not an array of char
The pointers in hostn are uninitialized, and thus don't point anywhere useful.
You pass the first element of hostn to strcpy as the destination
Since strcpy will attempt to dereference the pointer passed to it and that pointer is uninitialized, that means your program's behavior is undefined.
Note that all of this could be avoided easily. Just get rid of hostn entirely. It's not serving any purpose beyond what hostname.c_str() already serves. Simply change call_socket to accept a const char* instead of a char*, and you can call it directly using hostname.c_str() (i.e. call_socket(hostname.c_str(), s))

Visual C++ program complains about net framework

I wrote a simple client program in Visual C++ 2010 which connects to a client using winsock. When I try to run this program on another computer, it complains about missing Net Framework.
I wonder why that would be the case? What's in my code that requires net framework?
The error message:
application, you must first install one of the following versions of
the .NET Framework v4.0...etc
Here's my code
#pragma once
#pragma comment(lib, "Ws2_32.lib")
#include "stdafx.h"
#include <sdkddkver.h>
#include <WinSock2.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <time.h>
#include <cstring>
#include <sstream>
#define SCK_VERSION2 0x020
using namespace std;
void main() {
long Successful;
WSAData WinSockData;
WORD DLLVersion;
DLLVersion = MAKEWORD(2,1);
Successful = WSAStartup(DLLVersion, &WinSockData);
int sd,rcv,i,myint = 1;
hostent *host = gethostbyname("localhost");
char * myhostadd = inet_ntoa (*((struct in_addr *) host->h_addr_list[0]));
string memzi2,memzi,Converter;
char Message[200],tell[200] = "haa";
SOCKADDR_IN Address;
SOCKET sock;
sock = socket(AF_INET,SOCK_STREAM,NULL);
Address.sin_addr.s_addr = inet_addr(myhostadd);
Address.sin_family = AF_INET;
Address.sin_port = htons(7177);
cout << "Connecting to server...";
Successful = connect(sock, (SOCKADDR*)&Address, sizeof(Address));
u_long iMode=1;
ioctlsocket(sock,FIONBIO,&iMode);
if (Successful == 0) {
cout << "Connected. "<< endl;
for (;;++i) {
std::stringstream convert2;
convert2 << myint;
memzi2 = convert2.str();
std::cout << "Client: " << memzi2 << std::endl;
const char * c = memzi2.c_str();
sd = send(sock, c, sizeof(tell), NULL);
cout << "Server: ";
rcv = recv(sock,Message,sizeof(Message),NULL);
Converter = Message;
cout << Converter << endl;
std::stringstream convert1(Converter);
convert1 >> myint;
if (myint > 5000) {
myint = 1;
}
++myint;
}
closesocket(sock);
}
else cout << "Failed." << endl;
cout << "\n\n\t";
system("pause");
exit(1);
}
Thanks in advance!
Can be a simple reason, it will be using C++ CLI, i.e. common language runtime. Go to project properties and fix it up, it will not show any more.

C++ Network program runs but give no output

My simple program gives no errors through the compiler and runs fine but it does not give the output it is supposed too until someone is connected. I have done a good bit of research and editing but can not figure it out.Also how do I let more than one person connect? Any help to get this to work would be appreciated. Thanks in advance!!! Code is below.
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
char msg[20];
using namespace std;
int main(int argc, char *argv[])
{
cout << "Made it to main!";
int listener_d = socket(PF_INET, SOCK_STREAM, 0);
struct sockaddr_in name;
name.sin_family = PF_INET;
name.sin_port = (in_port_t)htons(30000);
name.sin_addr.s_addr = INADDR_ANY;
if(bind (listener_d, (struct sockaddr *) &name, sizeof(name)) == -1)
{
cout << "Can't bind the port!";
}
else
{
cout << "The port has been bound.";
}
listen(listener_d, 10);
cout << "Waiting for connection...";
while(1)
{
struct sockaddr_storage client_addr;
unsigned int address_size = sizeof(client_addr);
int connect_d = accept(listener_d, (struct sockaddr *)&client_addr, &address_size);
cin >> msg;
send(connect_d, msg, strlen(msg), 0);
}
return 0;
}
Maybe you should try flushing the output.
std::cout << "Waiting for connection..." << std::flush;

Target address reversed

I use to code in Python. Now I'm trying C++. When I run the program I see the target address (w/ Wireshark) reverse, even if I use htonl. In Python this same program worked fine.
Follow the code. At the bottom I printed the result.
I'm using Ubuntu 12.04LTS and g++ (Ubuntu/Linaro 4.6.3).
//UdpClient.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <cstdlib>
#include <arpa/inet.h>
#include <typeinfo>
using namespace std;
int main(int argc, char* argv[])
{
int s, p, rb,rs;
int bytesend;
char buf[1024];
int len;
char ent[16];
char Porta[5];
unsigned long EndServ;
struct sockaddr_in UdpServer, UdpClient;
int UdpServerLen = sizeof(UdpServer);
//do text
string msg("The quick brown fox jumps over the lazy dog\n");
len = msg.copy(buf, msg.size(), 0);
buf[len] = '\0';
//do socket
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == -1){
cout << "No socket done\n";
}
else {
cout << "Socket done\n";
}
//populate UdpClient struct
UdpClient.sin_family = AF_INET;
UdpClient.sin_addr.s_addr = INADDR_ANY;
UdpClient.sin_port = 0;
//populate UdpServer struct
UdpServer.sin_family = AF_INET;
UdpServer.sin_addr.s_addr = inet_addr(argv[1]);
//check if addres is correct
cout << "ServerAddress: " << hex << UdpServer.sin_addr.s_addr << endl;
UdpServer.sin_port = htons(atoi(argv[2]));
//bind socket
rb = bind(s, (struct sockaddr *)&UdpClient, sizeof(UdpClient));
if (rb == 0){
cout << "Bind OK!\n";
}
else {
cout << "Bind NOK!!!\n";
close(s);
exit(1);
}
//send text to Server
cout << "UdpServSiz: " << sizeof(UdpServer) << endl;
rs = sendto(s, buf, 1024, 0, (struct sockaddr *)&UdpServer, sizeof(UdpServer));
if (rs == -1){
cout << "Message NOT sent!!!\n";
}
else {
cout << "Message SENT!!!\n";
}
close(s);
return 0;
}
/*
edison#edison-AO532h:~/CmmPGMs$ ./UdpClient 127.0.0.1 6789
Socket done
ServerAddress: 100007f (using htonl or not!!)
Bind OK!
Message SENT!!!
edison#edison-AO532h:~/CmmPGMs$
*/
Sounds like you're on ARM (Linaro)? In which case the endianness of the processor matches network order, so htonl and ntohl basically do nothing.

VC11 Winsock Application Won't Shut Down

I have an interesting scenario for a winsock app that seemingly will not close. The following is enough code to fully replicate the issue:
#include "stdafx.h"
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#include <WS2tcpip.h>
#include <MSTcpIP.h>
#include <ws2ipdef.h>
#include <cstdio>
#include <iostream>
using namespace std;
int main() {
WSAData wsaStartup;
WSAStartup(MAKEWORD(2, 2), &wsaStartup);
SOCKET s = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
addrinfo *result;
addrinfo hint = { 0 };
hint.ai_family = AF_INET6;
int error = getaddrinfo("localhost", "45000", &hint, &result);
if (error || !result) {
cout << "Unable to resolve host. " << WSAGetLastError() << endl;
return 1;
}
error = connect(s, result->ai_addr, result->ai_addrlen);
if (error == SOCKET_ERROR) {
cout << "Unable to connect to host. " << WSAGetLastError() << endl;
} else {
cout << "Connection successful." << endl;
}
freeaddrinfo(result);
closesocket(s);
WSACleanup();
return 0;
}
I have spent numerous hours trying to track the issue down. It seems like getaddrinfo and connect both spawn an nt thread that hangs out, and prevents the app from terminating.
The only important compiler option that I changed here is: Linker->Advanced->EntryPoint where I specified "main". If I get rid of that compiler option, and change the main signature to:
int _tmain(int argc, _TCHAR* argv[])
everything seems to work fine. In my use case, I am fine having the above _tmain function, but I am wondering if anyone has any idea what magic is going on behind the scenes of the _tmain function that is making the app close.
How do I correctly set the entry point for an exe in Visual Studio?
Perhaps you need to provide the correct signature for main() to match what the runtime is expecting.