http request using sockets on c++ - c++

I'm trying to do an HTTP request using sockets on Linux, and my function works now, but only with simple domains as www.google.com or webpage.000webhostapp.com. When I try to add a path and query like webpage.000webhostapp.com/folder/file.php?parameter=value, it starts failing.
This is my code:
#include <iostream>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
int main(){
int socket_desc;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
std::string url = "www.exampleweb.com/folder/file.php";
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if(socket_desc < 0){
std::cout<<"failed to create socket"<<std::endl;
}
server = gethostbyname(url.c_str());
if(server==NULL){std::cout<<"could Not resolve hostname :("<<std::endl;}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(80);
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
if(connect(socket_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
std::cout<<"connection failed :("<<std::endl;
}
std::string request = "GET / HTTP/1.1\r\nHost: " + url + "\r\nConnection: close\r\n\r\n";
if(send(socket_desc, request.c_str(), strlen(request.c_str())+1, 0) < 0){
std::cout<<"failed to send request..."<<std::endl;
}
int n;
std::string raw_site;
while((n = recv(socket_desc, buffer, sizeof(buffer)+1, 0)) > 0){
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'){
raw_site+=buffer[i];
i += 1;
}
}
std::cout<<raw_site<<std::endl;
return 0;
}
Using www.google.com, it works perfectly for the request.
Using www.example.com/folder/file.php?parameter=value&parameter2=value2, it fails and returns "could not resolve hostname".
Any idea on how to fix it?
I'm not using curl and can't use it for this project.

gethostbyname() (which BTW is deprecated, you should be using getaddrinfo() instead) does not work with URLs, only with host names.
Given a URL like http://www.exampleweb.com/folder/file.php?parameter=value&parameter2=value2, you need to first break it up into its constituent pieces (read RFC 3986), eg:
the scheme http
the host name www.exampleweb.com
the resource path /folder/file.php
the query ?parameter=value&parameter2=value2
You can then resolve the IP address for the host, connect to that IP address on port 80 (the default port for HTTP) since the URL doesn't specify a different port, and finally send a GET request for the resource and query.
Also, note that the Host header in the GET request must specify only the host name (and port, if different than the default), not the whole URL. And also that HTTP requests are not null-terminated strings, so do not send the null terminator. Read RFC 2616.
Try this instead:
#include <iostream>
#include <cstring>
#include <string>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
int main(){
int socket_desc;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
std::string host = "www.exampleweb.com";
std::string port = "80";
std::string resource = "/folder/file.php";
std::string query = "?parameter=value&parameter2=value2";
socket_desc = socket(AF_INET, SOCK_STREAM, 0);
if (socket_desc < 0){
std::cout << "failed to create socket" << std::endl;
return 0;
}
server = gethostbyname(host.c_str());
if (server == NULL){
std::cout << "could Not resolve hostname :(" << std::endl;
close(socket_desc);
return 0;
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(std::stoi(port));
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
if (connect(socket_desc, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
std::cout << "connection failed :(" << std::endl;
close(socket_desc);
return 0;
}
std::string request = "GET " + resource + query + " HTTP/1.1\r\nHost: " + host + "\r\nConnection: close\r\n\r\n";
if (send(socket_desc, request.c_str(), request.size(), 0) < 0){
std::cout << "failed to send request..." << std::endl;
close(socket_desc);
return 0;
}
int n;
std::string raw_site;
while ((n = recv(socket_desc, buffer, sizeof(buffer), 0)) > 0){
raw_site.append(buffer, n);
}
close(socket_desc);
std::cout << raw_site << std::endl;
return 0;
}

Related

cannot send nor receive data through sockets

I tried making a simple server-client socket communication but something seems to no work properly with the server. I get this error whenever I send or receive:
Socket operation on non-socket: Socket operation on non-socket
Strangely enough, this only appears whenever the server is sending.
the client seems to be ok:
//server
#include <iostream>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
using namespace std;
int main(){
const int PORT = 5000;
int serverfd, clientfd, opt=1, n_send, n_recv;
sockaddr_in server_address, client_address;
char recvbuf[1024], sendbuf[1024];
bzero(&server_address , sizeof(server_address));
inet_pton(AF_INET, "127.0.0.1",&server_address.sin_addr);
int x = INADDR_ANY;
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
socklen_t addrSize = sizeof(server_address);
if((serverfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((bind(serverfd, (sockaddr*)&server_address, sizeof(server_address)))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((listen(serverfd, 1))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if((clientfd = accept(serverfd, (sockaddr *)&server_address, (socklen_t*)&addrSize) < 0)){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
while (true){
cout << "SAY TO CLIENT: ";
bzero(sendbuf, sizeof(sendbuf));
cin >> sendbuf;
cout << endl;
send(clientfd, sendbuf, strlen(sendbuf), 0);
errno = 0;
bzero(recvbuf, sizeof(recvbuf));
if((n_recv = recv(clientfd, recvbuf, sizeof(recvbuf), MSG_WAITALL))< 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
cout << recvbuf << endl;
}
return 0;
}
//client
#include <iostream>
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <arpa/inet.h>
using namespace std;
int main(){
const int PORT = 5000;
int sockfd, n_send, n_recv;
char recvbuf[1024], sendbuf[1024];
sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family= AF_INET;
server_address.sin_port = htons(PORT);
inet_pton(AF_INET, "127.0.0.1", &server_address.sin_addr);
if((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
if(connect(sockfd, (sockaddr *) &server_address, sizeof(server_address))<0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
while (true){
if((n_recv = recv(sockfd, recvbuf, sizeof(recvbuf), MSG_WAITALL)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
cout << "Server: " << recvbuf << endl;
cout << "Say to server: ";
cin >> sendbuf;
cout << endl;
if((n_send = send(sockfd, sendbuf, sizeof(sendbuf), 0)) < 0){
perror(strerror(errno));
exit(EXIT_FAILURE);
}
}
return 0;
}
clientfd is assigned a non-socket value. If we change the whitespace in your if:
if((clientfd =
accept(serverfd, (sockaddr *)&server_address, (socklen_t*)&addrSize) < 0
)) {
perror(strerror(errno));
exit(EXIT_FAILURE);
}
Because of the way you wrote it, the result of accept (the presumably valid socket) is checked, and that result is set to clientFd. Note that your parenthesis placement doesn't match your other lines.

HTTP errors while making a request through a proxy

I want to know how to make an HTTP request through a proxy using Socket.
I was looking through documentation on Internet, and many people said that to do it I must connect to the proxy server and send a packet with the following header:
send(Socket, "CONNECT http://icanhazip.com:80 HTTP/1.0\r\n\r\n", strlen("CONNECT http://icanhazip.com:80 HTTP/1.0\r\n\r\n"), 0);
That website returns the current public IP, but, unfortunately, every proxy server I tried returned errors instead of the webpage's HTML source.
This is my actual code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
try {
int Socket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = inet_addr("198.169.246.30");
int iResult = connect(Socket, (struct sockaddr *)& SockAddr, sizeof(SockAddr));
if (iResult != 0) {
std::cout << "I can't connect :(.";
getchar();
return 1;
}
std::cout << "Connected.\n";
send(Socket, "CONNECT http://icanhazip.com:80 HTTP/1.1\r\n\r\n", strlen("CONNECT http://icanhazip.com:80 HTTP/1.1\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
iResult = close(Socket);
}
catch (...) {
}
return 0;
}
What can I do to fix it? Or, what other solution should I look into?
Old Chinese proverb say, "before writing code, better to read specification"
https://www.rfc-editor.org/rfc/rfc7230
by following links in the document:
A client sending a CONNECT request MUST send the authority form of
request-target (Section 5.3 of [RFC7230]); i.e., the request-target
consists of only the host name and port number of the tunnel
destination, separated by a colon. For example,
CONNECT server.example.com:80 HTTP/1.1
Host: server.example.com:80
source: https://www.rfc-editor.org/rfc/rfc7231#section-4.3.6

Making an HTTP Request with Sockets through a proxy

I would like to make an HTTP request using sockets. Here is my code so far:
#include "stdafx.h"
#ifndef UNICODE
#define UNICODE
#endif
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
try {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
sockaddr_in clientService;
SOCKET Socket = socket(AF_INET, SOCK_STREAM, 0);
memset(&clientService, 0, sizeof(clientService));
clientService.sin_addr.s_addr = inet_addr("83.233.53.59"); // Proxy IP
clientService.sin_family = AF_INET;
clientService.sin_port = htons(10200);
if (bind(Socket, (struct sockaddr *) &clientService, sizeof(clientService)) < 0) {
perror("bind");
exit(1);
}
system("pause");
return 0;
struct hostent *host;
host = gethostbyname("www.google.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
// SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
memcpy(host->h_addr, &(SockAddr.sin_addr.s_addr), host->h_length);
std::cout << "Connecting...\n";
iResult = connect(Socket, (SOCKADDR *)& clientService, sizeof(clientService));
if (iResult != 0) {
std::cout << "Could not connect";
getchar();
return 1;
}
std::cout << "Connected.\n";
send(Socket, "GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
iResult = closesocket(Socket);
WSACleanup();
system("pause");
}
catch (...) {
system("pause");
}
return 0;
}
But it doesn't work, without the program closes itself without leaving me the HTML source of the webpage. What's wrong?
How can I fix it?
This works on my machine, but I'm not on a windows machine. I'm on a freeBSD (OS X) machine. Having problems getting gethostbyname to resolve, not sure what that's about, but this worked and connected and downloaded the code from google.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define WIN32_LEAN_AND_MEAN
//#include <winsock2.h>
//#include <ws2tcpip.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
try {
// WSADATA wsaData;
// int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
// sockaddr_in clientService;
int Socket = socket(AF_INET, SOCK_STREAM, 0);
/*
memset(&clientService, 0, sizeof(clientService));
clientService.sin_addr.s_addr = inet_addr("83.233.53.59"); // Proxy IP
clientService.sin_family = AF_INET;
clientService.sin_port = htons(10200);
if (bind(Socket, (struct sockaddr *) &clientService, sizeof clientService) == -1) {
perror("bind");
exit(1);
}
system("pause");
return 0;
*/
const char hostname[] ="www.google.com";
struct hostent * host;
// host = gethostbyname(hostname);
sockaddr_in SockAddr;
memset(&SockAddr, 0, sizeof(SockAddr));
SockAddr.sin_port = htons(80);
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = inet_addr("83.233.53.59");
// memcpy(host->h_addr, &(SockAddr.sin_addr.s_addr), host->h_length);
std::cout << "Connecting...\n";
int iResult = connect(Socket, (struct sockaddr *)& SockAddr, sizeof(SockAddr));
if (iResult != 0) {
std::cout << "Could not connect";
getchar();
return 1;
}
std::cout << "Connected.\n";
send(Socket, "GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP / 1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n"), 0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0) {
int i = 0;
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
std::cout << buffer[i];
i += 1;
}
}
iResult = close(Socket);
// WSACleanup();
system("pause");
}
catch (...) {
system("pause");
}
return 0;
}
It had an authentication failure at the http: level, but Heres the output:
Connecting...
Connected.
HTTP/1.0 401 Unauthorized
Server: uhttpd/1.0.0
Date: Thu, 17 Dec 2015 18:29:04 GMT
WWW-Authenticate: Basic realm=" "
Content-Type: text/html; charset="UTF-8"
Connection: close
<HTML><HEAD><META http-equiv='Pragma' content='no-cache'><META http-equiv='Cache-Control' content='no-cache'><TITLE> 401 Authorization</TITLE>
<script language=javascript type=text/javascript>
function cancelevent()
{
sh: pause: command not found
Program ended with exit code: 0
One thing that might go wrong is that your application may crash when it accesses an out-of-bound array index during the following loop:
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r') {
...
i += 1;
}
Your current code cannot guarantee the buffer contains a byte that would make your loop terminate, therefore it might continue indefinitely. You must prevent this by having an extra check before accessing the array index. Considering that nDataLength will always be smaller or equal to sizeof(buffer), try this:
while (i < nDataLength &&
(buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r'))
{
// Do your printing.
i++;
}
Or maybe simpler:
while (buffer[i] >= 32 || buffer[i] == '\n' || buffer[i] == '\r')
{
// Do your printing.
i++;
if (i >= nDataLength)
break; // Exit the loop.
}
system("pause");
return 0;
This code prevents anything following from executing. Remove.
There are numerous other problems with your code. For example, you're binding the socket to the proxy address. That doesn't make sense. Remove. You're about to connect the socket, you don't need to bind it at all.
Then you're sending an invalid GET request to the proxy. The GET request in this case should contain the full URL, not just a relative URL.
You're overrunning the receive buffer when you search for the space etc. You need to bound that search by the count returned by recv().
And so on.

C++ sockets can't receive more than 21845 bytes

I have simple webserver:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>
#include <string.h>
#include <boost/regex.hpp>
#include <boost/thread.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string.hpp>
#include "print_r.h"
#include "Pop.h"
#include "Headers.h"
//#include<thread>
char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n"
"Connection: keep-alive\r\n"
"Server: michal\r\n"
"Set-Cookie: nazwa=test\r\n"
"Date: Mon, 24 Feb 2014 11:39:26 GMT\r\n"
"Vary: Accept-Encoding\r\n\r\n"
"<html><body><h1>It works!</h1>"
"<p>This is the default web page for this server.</p>"
"<p>The web server software is running but no content has been added, yet.</p>"
"<form method='post' action='/' enctype='multipart/form-data' ><input type='file' name='pliczek1'/><input type='submit' name='sub' value='sender' /><input type='checkbox' name='add[]' value='100001_used' ><input type='hidden' name='hidd' value='testowy hiddenik' /><input type='checkbox' name='add[]' value='100002_used' ><textarea name='txtform'>tekstowe poleąś</textarea></form>"
"</body></html>\r\n\r\n";
void app(int client_fd)
{
int buffSize = 512;
char buff[buffSize];
std::string headers = "";
int i = 0;
int npos = 0;
int a = 0;
while (i = recv(client_fd, buff, buffSize, 0))
{
std::cout << i << "\n";
bzero(buff, buffSize);
a++;
if (i < buffSize) break;
}
write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/
close(client_fd);
}
int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);
std::cout << sizeof(cli_addr);
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
int port = 8080;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}
listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
std::cout << "\n\n+++++++++++++ NEW CLIENT +++++++++++++++\n\n\n";
if (client_fd == -1) {
std::cout << ("Can't accept\n");
break;
}
app(client_fd);
}
}
I am trying to send an attachment via the web browser. With files smaller than 21kB it works fine but I can't send more than 21845 bytes. Why?
You broke a very important rule: Always check the return value of API calls.
In particular, you don't check the return value of write, you just assume it succeeds. In reality, it often only sends part of the message, so you need a loop and error checking.
Try to read with a small delay between recv calls. You are not guaranteed to receive all data in one go. You have to wait for all the data.

c++: read() Hangs when reading response from server

I have two versions of this code. In one version if the user inputs the phrase "GET /index.html" the server responds properly. In the second version, the "GET /index.html" phrase is built in without prompting the user. The second version hangs when reading a response from the server, any idea why?
First Version - Prompts user for phrase
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[10000];
portno = atoi("85");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error((char *)"ERROR opening socket");
server = gethostbyname("vilive.us");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error((char *)"ERROR connecting");
printf("Please enter the message: ");
memset(buffer,0,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error((char *)"ERROR writing to socket");
memset(buffer,0,256);
n = read(sockfd,buffer,500);
if (n < 0)
error((char *)"ERROR reading from socket");
printf("%s\n",buffer);
return 0;
}
Second Version - Automatically sends "GET /index.html" - This one hangs
#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[10000];
//TEST
char getI[16];
getI[0]='G';
getI[1]='E';
getI[2]='T';
getI[3]=' ';
getI[4]='/';
getI[5]='i';
getI[6]='n';
getI[7]='d';
getI[8]='e';
getI[9]='x';
getI[10]='.';
getI[11]='h';
getI[12]='t';
getI[13]='m';
getI[14]='l';
getI[15]='\0';
portno = atoi("85");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error((char *)"ERROR opening socket");
server = gethostbyname("vilive.us");
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy((char *)&serv_addr.sin_addr.s_addr, (char *)server->h_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error((char *)"ERROR connecting");
/*printf("Please enter the message: ");
memset(buffer,0,256);
fgets(buffer,255,stdin);*/
n = write(sockfd,getI,strlen(getI));
if (n < 0)
error((char *)"ERROR writing to socket");
memset(buffer,0,256);
n = read(sockfd,buffer,500);
if (n < 0)
error((char *)"ERROR reading from socket");
printf("%s\n",buffer);
return 0;
}
The request must be terminated with 2 carriage return and line feed pairs, this is missing in your second example.
char charI[] = "GET /index.html\r\n\r\n";
Please, switch to a modern version of HTTP. I find it amazing that your server agrees to reply, as the request isn't remotely valid HTTP.
This would be a suitable HTTP/1.1 request in your situation
char charI[] = "GET /index.html HTTP/1.1\r\nHost: vilive.us\r\nConnection: close\r\n\r\n";
note the Host header, that allow you to talk with sites that do virtual hosting, like ... stackoverflow.com and superuser.com that points to the same ip address. they only rely on the Host header to figure out if the user want to access stackoverflow.com or superuser.com.
Also, your should close the socket descriptor when you are done using the socket.