tags:

views:

243

answers:

3

Hi,

In C++, if I have a socket, how can I create an ostream object from it?

I have googled some example: http://members.aon.at/hstraub/linux/socket++/docu/socket++_10.html

And i have tried: sockbuf sb(sockfd); std::ostream outputStream(&sb);

But I can't find the .h file and the library to link with for 'sockbuf'. Is that part of a standard c++ library?

Thank you.

+7  A: 

The site you found is a third party non-standard library. There is no standard C++ socket library.

However, if you want as closest to a standard (and powerful!) solution, you should try Boost.Asio. It has been proposed for inclusion in the standard library (TR2). Here's an iostream based example:

boost::asio::ip::tcp::iostream stream("www.example.org", "http");
stream << "GET / HTTP/1.0\r\nHost: www.boost.org\r\n\r\n" << std::flush;

std::string response;
std::getline( stream, response );

However, you'd gain much more if using the Asio's Proactor for asynchronous operation.

Kornel Kisielewicz
+1 for Asio reference. :-)
Chris Jester-Young
@Chris, I learned to love and value it after working 1 year writing commercially a C++ server, and then seeing how easy it is with Asio :)
Kornel Kisielewicz
+1  A: 

It is not part of the standard C++ library. Download Socket++ here: http://members.aon.at/hstraub/linux/socket++/ (it was a few directories back from what you pasted)

Chris Dennett
+2  A: 

Standard C++ (at least C++98) does not deal with networking in any way. So, you have to do something platform-specific.

Some platforms have IOStreams implementations that allow you to create a stream from a file descriptor. In that case, use the socket descriptor as your file descriptor.

Chris Jester-Young
+1: I'd never think of actually passing a `fd` to an iostream O.o
Kornel Kisielewicz
I am writing my application on ubuntu. Does it has IOStreams which allows me to create a stream from a socket? How can I look for that?
silverburgh
@silverburgh: GCC 3.4 onwards, so I hear, has `__gnu_cxx::stdio_filebuf`, which you can use for that. This article is worth paying attention to: http://www.synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html
Chris Jester-Young
Thanks. But after reading that link, and google more about it, I think stdio_filebuf is for file not for socket.
silverburgh