Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a bad file descriptor error?

I am trying to write a short program that acts like a client, like telnet. I receive from the user input like so: www.google.com 80 (the port number) and /index.html However, I get some errors. When I write some debug information, it says that I have a bad file descriptor and Read Failed on file descriptor 100 messagesize = 0.

struct hostent * pHostInfo;
struct sockaddr_in Address;
long nHostAddress;
char pBuffer[BUFFER_SIZE];
unsigned nReadAmount;
int nHostPort = atoi(port);

vector<char *> headerLines;
char buffer[MAX_MSG_SZ];
char contentType[MAX_MSG_SZ];

int hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (hSocket == SOCKET_ERROR)
{
  cout << "\nCould Not Make a Socket!\n" << endl;
  return 1;
}
pHostInfo = gethostbyname(strHostName);
memcpy(&nHostAddress,pHostInfo -> h_addr, pHostInfo -> h_length);

Address.sin_addr.s_addr = nHostAddress;
Address.sin_port=htons(nHostPort);
Address.sin_family = AF_INET;

if (connect(hSocket, (struct sockaddr *)&Address, sizeof(Address)) == SOCKET_ERROR)
{
  cout << "Could not connect to the host!" << endl;
  exit(1);
}
char get[] = "GET ";
char http[] = " HTTP/1.0\r\nHost: ";
char end[] = "\r\n\r\n";
strcat(get, URI);
strcat(get, http);
strcat(get, strHostName);
strcat(get, end);
strcpy(pBuffer, get);
int len = strlen(pBuffer);
send(hSocket, pBuffer, len, 0);
nReadAmount = recv(hSocket,pBuffer, BUFFER_SIZE, 0);
//Parsing of data here, then close socket
if (close(hSocket) == SOCKET_ERROR)
{
  cout << "Could not close the socket!" << endl;
  exit(1);
} 

Thanks!

like image 240
Guybrush Threepwood Avatar asked Dec 27 '22 14:12

Guybrush Threepwood


1 Answers

You have a buffer overrun in your code. You're attempting to allocate a bunch of character arrays together into a buffer than is only 5 bytes long:

char get[] = "GET ";  // 'get' is 5 bytes long
char http[] = " HTTP/1.0\r\nHost: ";
char end[] = "\r\n\r\n";
strcat(get, URI);  // BOOM!
strcat(get, http);
strcat(get, strHostName);
strcat(get, end);

This is likely overwriting your local variable hSocket, resulting in the "bad file descriptor error".

Since you're using C++ (you have a vector in your code), just use a std::string instead of C arrays of characters so that you don't have to worry about memory management.

like image 118
Adam Rosenfield Avatar answered Jan 14 '23 15:01

Adam Rosenfield