473,786 Members | 2,407 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Example of using sockets/http

I am looking for a simple sample of using sockets to download a page
into a string. If anyone knows where I could get a sample, or post one
here, that would be great.

Dec 31 '05 #1
9 6646
Mike Curry wrote:
I am looking for a simple sample of using sockets to download a page
into a string. If anyone knows where I could get a sample, or post one
here, that would be great.


Why are you using C++?

Scripting languages like Ruby come with HTTP libraries to do that in a
couple function calls.

You could also shell to wget or lynx like this:

system("lynx -source http://myserver/mypage > aFile.html");

now read aFile.html

If you write that from scratch, with sockets, you will have to debug it for
various protocols and network conditions. Just re-use what's out there...

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Dec 31 '05 #2
How different is Ruby from C++, and is it as fast as C++? It also has
to be cross platform, windows/linux.

Dec 31 '05 #3
Mike Curry wrote:
How different is Ruby from C++, and is it as fast as C++? It also has
to be cross platform, windows/linux.

http://www.ruby-lang.org/en/
Dec 31 '05 #4
Hi,

Here is how to connect to Host:Port i.e.string Host = "www.host.c om"; int
Port = 80;

Note:

Socket is an int on unix type of systems but SOCKET on windows.

#define closesocket as close on unix type systems.

Do Connect. The code is pretty much cross platform (I have used it on linux
and lot's of unices as well as windows) You have to check your OS for the
headers to include though. On MS-Windows platforms you have to initialize
the stack (from the top of my head WSAStartup or somethig like that) and
during linktime you have include the appropriate library (I believe inet.lib
but just search for select on MSDN and scroll down). For Sun-os you also
have to add some libraries (just do a man -k select or something like that
to get the correct manual pages).
bool CBaseSocket::In it()
{
struct protoent *PE = getprotobyname( "tcp" );
if( PE ) ProtoNumber = PE->p_proto;
else ProtoNumber = 6; // Otherwise select proto anyway

struct hostent *pHE;

//memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_port = htons( Port );

// Try as dotted notation e.g. 192.168.1.1
sin.sin_addr.s_ addr = inet_addr( Host.c_str() );
if( sin.sin_addr.s_ addr != -1 )return true;

// Try as labels e.g. moonlit.xs4all. nl
if( ( pHE = gethostbyname( Host.c_str() ) ) == NULL )
{
LastError = string( "Couldn't get name" );
return false;
}

sin.sin_addr.s_ addr = *reinterpret_ca st<unsigned long*>(
*pHE->h_addr_list );

return true;
}
bool CBaseSocket::Co nnect()
{
bool RetVal = true;

if( !Init() )
{
LastError = string( "Couldn't convert address" );
Log << Level2 << LastError << End;
return false;
}

if( ( Socket = static_cast<SOC KET>( socket( AF_INET, SOCK_STREAM, 0 ) ) )
== INVALID_SOCKET )
{
LastError = string( "Error creating client Socket" );
Log << Level2 << LastError << End;
return false;
}

if( connect( Socket, (struct sockaddr*)&sin, sizeof( sin ) ) ==
SOCKET_ERROR )
{
LastError = string( "Couldn't connect to" );
Log << Level2 << LastError << End;
closesocket( Socket );
return false;
}

unsigned long True = 1;
ioctlsocket( Socket, FIONBIO, &True ); // Hope this works (undocumented)?
setsockopt( Socket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cas t<char*>(
&True ), sizeof( True ) );

return true;
}








--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"Mike Curry" <mm*****@rogers .com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
I am looking for a simple sample of using sockets to download a page
into a string. If anyone knows where I could get a sample, or post one
here, that would be great.

Jan 1 '06 #5
Looking at the code I forgot:

#define INVALID_SOCKET -1

on unix systems

--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"Moonlit" <news moonlit xs4all nl> wrote in message
news:43******** *************** @news.xs4all.nl ...
Hi,

Here is how to connect to Host:Port i.e.string Host = "www.host.c om";
int Port = 80;

Note:

Socket is an int on unix type of systems but SOCKET on windows.

#define closesocket as close on unix type systems.

Do Connect. The code is pretty much cross platform (I have used it on
linux and lot's of unices as well as windows) You have to check your OS
for the headers to include though. On MS-Windows platforms you have to
initialize the stack (from the top of my head WSAStartup or somethig like
that) and during linktime you have include the appropriate library (I
believe inet.lib but just search for select on MSDN and scroll down). For
Sun-os you also have to add some libraries (just do a man -k select or
something like that to get the correct manual pages).
bool CBaseSocket::In it()
{
struct protoent *PE = getprotobyname( "tcp" );
if( PE ) ProtoNumber = PE->p_proto;
else ProtoNumber = 6; // Otherwise select proto anyway

struct hostent *pHE;

//memset( &sin, 0, sizeof sin );
sin.sin_family = AF_INET;
sin.sin_port = htons( Port );

// Try as dotted notation e.g. 192.168.1.1
sin.sin_addr.s_ addr = inet_addr( Host.c_str() );
if( sin.sin_addr.s_ addr != -1 )return true;

// Try as labels e.g. moonlit.xs4all. nl
if( ( pHE = gethostbyname( Host.c_str() ) ) == NULL )
{
LastError = string( "Couldn't get name" );
return false;
}

sin.sin_addr.s_ addr = *reinterpret_ca st<unsigned long*>(
*pHE->h_addr_list );

return true;
}
bool CBaseSocket::Co nnect()
{
bool RetVal = true;

if( !Init() )
{
LastError = string( "Couldn't convert address" );
Log << Level2 << LastError << End;
return false;
}

if( ( Socket = static_cast<SOC KET>( socket( AF_INET, SOCK_STREAM, 0 ) ) )
== INVALID_SOCKET )
{
LastError = string( "Error creating client Socket" );
Log << Level2 << LastError << End;
return false;
}

if( connect( Socket, (struct sockaddr*)&sin, sizeof( sin ) ) ==
SOCKET_ERROR )
{
LastError = string( "Couldn't connect to" );
Log << Level2 << LastError << End;
closesocket( Socket );
return false;
}

unsigned long True = 1;
ioctlsocket( Socket, FIONBIO, &True ); // Hope this works (undocumented)?
setsockopt( Socket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cas t<char*>(
&True ), sizeof( True ) );

return true;
}








--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"Mike Curry" <mm*****@rogers .com> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
I am looking for a simple sample of using sockets to download a page
into a string. If anyone knows where I could get a sample, or post one
here, that would be great.


Jan 1 '06 #6
The major topic here is simply "horses for courses". C++ is a good student
language and good system language. Many simpler and higher-level languages
are better for the high-level glue code we write to bind systems together.

Mike Curry wrote:
How different is Ruby from C++,
Ruby (similar to Python, Perl, etc.) comes from only one distribution, so
its maintainers can bundle any library works. (Also, such libraries are
suspiciously easy to write. Ruby bundles with Webrick, for example, which is
a small and full-featured web server.)
and is it as fast as C++?
You can write complex programs in Ruby much faster than you can in C++.

And a program that uses HTTP will be IO-bound by nature, so the mild
performance hit using an interpreted language is negligible.
It also has
to be cross platform, windows/linux.


Because Ruby comes from one distribution, the maintainers can add libraries
to it that are as portable as it is.

Ruby can work on any platform that supports Standard C, and it has
installers for all the major Linuces and for Windows.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Jan 1 '06 #7
Moonlit wrote:

Thank you! That's the example which would be 2-4 lines of code in a higher
level language, but it's always nice to know I can Google for this post when
I need C++.

Anecdote: Just last fall I put in similar code to a C++ script I wrote
(against my advice here), and have since simplified everything else enough
to take it out. ;-)
Looking at the code I forgot:

#define INVALID_SOCKET -1


Hmm. Sometimes we claim that all such #defines should be 'static const int'
instead.

Can anyone think of a linguistic reason that this must be a #define?

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Jan 1 '06 #8
Hi,

--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"Phlip" <ph******@yahoo .com> wrote in message
news:Kk******** *******@newssvr 30.news.prodigy .com...
Moonlit wrote:

Thank you! That's the example which would be 2-4 lines of code in a higher
level language, but it's always nice to know I can Google for this post
when I need C++.

Anecdote: Just last fall I put in similar code to a C++ script I wrote
(against my advice here), and have since simplified everything else enough
to take it out. ;-)
Looking at the code I forgot:

#define INVALID_SOCKET -1
Hmm. Sometimes we claim that all such #defines should be 'static const
int' instead.


Oops, yes you are absolutely right. I just checked the complete class and
saw that I actually had them both and used both :-(. Ok, time to clean up
some stuff I guess, thanks for triggering me.
Can anyone think of a linguistic reason that this must be a #define?

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!

Jan 1 '06 #9

Mike Curry wrote:
I am looking for a simple sample of using sockets to download a page
into a string. If anyone knows where I could get a sample, or post one
here, that would be great.


Sockets might be to complicated for a starter. Try libcurl.
http://curl.planetmirror.com/libcurl/c/example.html

Jan 1 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
3086
by: Snyke | last post by:
I'm currently looking for a good C++ Wrapper for sockets. I've already tried http://www.libsockets.net/ but I have some problems compiling it on Windows. Does anybody know a smaller (this library is pretty heavy after all) sockets wrapper?
10
2720
by: Cory Nelson | last post by:
I've created a new C++ sockets library - small, cross-platform, IPv4 and IPv6. If anyone would like to critique it, I'd appreciate it. Doesn't support the more exotic protocols - only TCP and UDP. It also lacks get/setsockopt and ioctl, but those may be added in the future. There is no webpage for it yet, I plan on making one once I'm 100% sure of everything. For now the source is available here: http://dev.int64.org/netx.zip PS....
4
1812
by: prashantkumar1982 | last post by:
I am using the select call to read from many sockets. I don't want to call read on every socket to check if it is closed, as it defeats the purpose of using the select call. Is there any way to know whether one of the sockets have been closed, without actually testing each socket.
3
1911
by: Mr Mind - Lion | last post by:
Please send me some sample for using Raw sockets. And also clearly specify that how can I set the ip header of the protocol. Please help me. Thanx.
2
2101
by: 1388-2/HB | last post by:
I've got a small sockets application where I communicate with a web server via async sockets method. Using the ASCIIEncoding Class, I convert strings to byte arrays (and vice versa) in conjunction with beginSend and beginReceive (and their corresponding callbacks). So long as the web server and I just deal in text, life is easy. Now there's an image I want to request and then display in my app, it's a dynamic PNG image that's...
4
3193
by: Marco Meoni | last post by:
Hi. I read the Gordon McMillan's "Socket Programming Howto". I tried to use the example in this howto but this doesn't work. The code is class mysocket: '''classe solamente dimostrativa - codificata per chiarezza, non per efficenza''' def __init__(self, sock=None): if sock is None: self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM) else:
2
24283
by: dariophoenix | last post by:
Hi, I am trying to encapsulate Linux sockets and POSIX threads in C++ classes (I work in Knoppix, using KDevelop). Since sockets and threads are new to me, I searched for example code and found the following: #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <netdb.h>
4
2168
by: billie | last post by:
Hi all. I'm (re)writing an FTP server application by using asyncore/asynchat modules. FTP tipically got two different channels: command and data. I'm succesfully managing command channel through asynchat framework, but I'm not sure about how to manage data channel without using a thread/subprocess. Is there an optimal to do that? Can anyone point me in the right direction?
6
1971
by: David | last post by:
http://msdn2.microsoft.com/en-us/library/bew39x2a(VS.80).aspx I was looking at above link and I just don't see the advantage of this. The main thread is just stopping and waiting for each of the connects/sends/receives to complete anyway so it seems to me using the synchronous methods would be much simpler and equivalent as far as efficiency/performance in this example? What am I missing here? Is it just that this example is simply to...
0
10360
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10163
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9960
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8988
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7510
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5397
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5532
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.