Pages

Friday, March 19, 2010

Make Free Calls


Make free call wer ever you want guyz..                    

NOTE: From the site "evaphone" you can call upto 25secnds in india.
and in Internationl see it "evadestinations" for timimng.

http://evaphone.com

http://evaphone.com/destinations

FROM THIS SITE YOU CAN CALL UPTO 10MINS...BY DOWNLOADING ITS PLUGINGS..

https://www.gizmocall.com/ 

Do 100% free calls 4m ur mobile and computer

well,der r many ways.
i m telling u all dem.
1 thing 2 keep in mind,methode [1]
in
case u wanna do free calls 4m ur mobile den
b4 of trying nexxt thing make sure dt u hv internet [gprs]in ur mobile set .
go on eqo.com nd register der.
while registering they will ask your mobile no. nd many more things .
give all d details der nw de vl send a link 2 ur mobile via sms.
nw click on dt sms nd a software vl be downloaded nw install dt.
and enjoi 100 free minutes 2 whole d world.
in case u want 2 install d software again in ur mobile den format ur mobile and insert a new sim nd apply d same procedure....
u can also install a software named mig33 in ur mobile.
it also do d same work.
search mig33 in google.






methode [2] it is 2 be done 4m computer
dis is a site http://www.mobivox.com




Features:-----------------


1. 10 Mints coll for free.
2. No Registration needed.
3.Better Voice Quality.
4.Quick N Active Response.


nw u will say dt it is giving only 10 calls.
no,dis is nt true.
u can do proxy and can do unlimited calls.
i hope u know hw 2 do proxy,if nt den refer my teaching hacking chapter 1. thread.


Last But not least U can coll ur self from ur number
http://www.youcall.com


https://www.tokiva.com




if u vl go on dese 2 sites den u can do free calss 4m dese sites also.


bt 4m ur computer.


How to do free calls to whole the world for free.

hello every1.
u might be wondering hw this is possible,
but it is
go 2
phonehog.com
and on
http://www.tuitalk.com/
on these two websites,first register the do free calls anywhere ..
once it says now you can not do more calls them register with another email id and hav fun again:P
in case you want to do free calls from your mobile then
go to
eqo.com
download there software and install in your mobile
it will give you 100 free minutes
and on
mig33.com
it will give you 3 free minutes.
for using mig33 and eqo your mobile must and must having gprs that moment:(
hav fun :P


Wanna tease ur friends by calling 4m their own number..?

If you want to tease or give shock to ur buddies by calling their mobile number 4m their own number(Just like self dialing)... You need to have a valid email id.. that's enough.. Now follow the following steps..

1. open http://www.mobivox.com/ in browser

2. Click on "register for free" link

3.  Fill all the details like 1st name and last name, but make sure that mobile number should be of the person whom you want to tease.. i.e. ur buddy's mobile number..

4. You must give a valid email id.. so that you will receive a url from mobivox web site. Pin can be any number(Better don't give ur mail's pswd)

5. After filling all the details.. just click on REGISTER..

6. Then open your mail.. and click on link sent by website..


7. Give your mail id and pin

8. After successfully logged in.. just click on "direct web call" link on the page...

9. It will ask you to enter a number.. This number can be of your choice.. If you want to get call from ur buddy.. give your number.. or else you can give any others number..

10. Your buddy's number will be automatically generated..

11. Then just click on call..

12. Your buddy will get a call from his own number

13. In no time you will get a call from his own number..

14. Both of you can speak together with ultimate for 5 free minutes..

15. If have any doubts.. post a reply..

16. If you really love it.. forward this link to as many friends as you can.. and spread smiles to all...

17. Please don't misuse this post.. Thank you..  

 last post  from my friend's blog :http://gettechtips.blogspot.com/ 

Hack another computer

NetBIOS Hacking
-What is it?-
NetBIOS Hacking is the art of hacking into someone else’s computer through your computer. NetBIOS stands for “Network Basic Input Output System.” It is a way for a LAN or WAN to share folders, files, drives, and printers.
-How can this be of use to me?-
Most people don’t even know, but when they’re on a LAN or WAN they could possibly have their entire hard drive shared and not even know. So if we can find a way into the network, their computer is at our disposal.

-What do I need?-
Windows OS
Cain and Abel (
http://www.oxid.it/)
++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++
-[Step 1, Finding the target.]-
++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++
So first off we need to find a computer or the computer to hack into. So if your plugged in to the LAN, or connected to the WAN, you can begin. Open up Cain and Abel. This program has a built in sniffer feature. A sniffer looks for all IP addresses in the local subnet. Once you have opened up the program click on the sniffer tab, click the Start/Stop sniffer, and then click the blue cross

Another window will pop up, make sure “All host in my subnet” is selected, and then click ok.

It should begin to scan.

Then IP’s, computer names, and mac addresses will show up.
Now remember the IP address of the computer you are going to be breaking into.
If you can’t tell whether the IP address is a computer, router, modem, etc, that’s ok.
During the next step we will begin our trial and error.

++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++
-[Part 2, Trial and Error]-
++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++

Now, we don’t know if we have our designated target, or if we have a computer or printer, or whatever else is on the LAN or WAN.
If you did get the IP of the target though, I still recommend reading through this section, for it could be helpful later on.
Click on the start menu and go to run, type in cmd, and click ok.

Raw sockets

Raw Socket is a software interface through which a process can fully control the packets it sends or receives to or from the network. This is done by bypassing the network stack of the host and communicating directly with the device driver.

Simply put we can use raw sockets to perform either of 2 tasks :

1. Packet Sniffing ( Receiving packets from raw socket )
2. Packet Injection ( Sending packets into raw socket )

For this discussion we will be limiting ourselves to the PF_PACKET interface on linux. In this discussion we will talk only about Packet Sniffing . Another discussion will cater to Packet Injection.

As you must have understood by now in the "Making of a Sniffer"  that we open a raw socket and start receiving packets from that interface. Once we receive a packet we should be able to parse that packet intelligibly and be able to find out the details of all the headers (Ethernet, IP, TCP , ARP, FTP etc).

Lets refresh our memory as to how the headers look like:

ethernet header
Ethernet Header
EthDHost :
Destination address (6 bytes).
EthSHost
Source address (6 bytes).
EthType
Encapsulated packet type (2 bytes). It is ETHERTYPE_IP for IP based communication.
Lets now look the IP header. Please look up the fields in the header if there is any confusion.
ip header tutorial 101 video
IP Header
Finally, the TCP and UDP headers look as below. After these headers, application specific data would be there.
tcp header 101 tutorial
TCP Header
udp header 101 tutorial video packet sniffing
UDP Header
Whenever our sniffer is receiving a packet it needs to know how to parse it. Assuming we are on an Ethernet Interface we will first parse the Ethernet Header to figure out what the packet contains by looking at the EthType field.

So how would an Ethernet Header look like in c code ? An IP header ? TCP ? UDP ? ....???
see the following code..

/* Injector.c */

Note: keep header files in tags ex:"<  >"
#include stdio.h
#include stdlib.h
#include sys/socket.h
#include features.h
#include linux/if_packet.h
#include linux/if_ether.h
#include errno.h
#include sys/ioctl.h
#include net/if.h
#include net/ethernet.h
#include linux/ip.h
#include linux/tcp.h
#include arpa/inet.h
#include string.h
#include sys/time.h



#define DATA_SIZE    100

#define SRC_ETHER_ADDR    "00:26:22:4f:bf:fa"
#define DST_ETHER_ADDR    "00:26:22:4f:bf:fa"
#define SRC_IP    "127.0.0.1"
#define DST_IP    "127.0.0.1"
#define SRC_PORT    2000
#define DST_PORT    2000

typedef struct PseudoHeader{

    unsigned long int source_ip;
    unsigned long int dest_ip;
    unsigned char reserved;
    unsigned char protocol;
    unsigned short int tcp_length;

}PseudoHeader;


int CreateRawSocket(int protocol_to_sniff)
{
    int rawsock;

    if((rawsock = socket(PF_PACKET, SOCK_RAW, htons(protocol_to_sniff)))== -1)
    {
        perror("Error creating raw socket: ");
        exit(-1);
    }

    return rawsock;
}

int BindRawSocketToInterface(char *device, int rawsock, int protocol)
{
  
    struct sockaddr_ll sll;
    struct ifreq ifr;

    bzero(&sll, sizeof(sll));
    bzero(&ifr, sizeof(ifr));
  
    /* First Get the Interface Index  */


    strncpy((char *)ifr.ifr_name, device, IFNAMSIZ);
    if((ioctl(rawsock, SIOCGIFINDEX, &ifr)) == -1)
    {
        printf("Error getting Interface index !\n");
        exit(-1);
    }

    /* Bind our raw socket to this interface */

    sll.sll_family = AF_PACKET;
    sll.sll_ifindex = ifr.ifr_ifindex;
    sll.sll_protocol = htons(protocol);


    if((bind(rawsock, (struct sockaddr *)&sll, sizeof(sll)))== -1)
    {
        perror("Error binding raw socket to interface\n");
        exit(-1);
    }

    return 1;
  
}


int SendRawPacket(int rawsock, unsigned char *pkt, int pkt_len)
{
    int sent= 0;

    /* A simple write on the socket ..thats all it takes ! */

    if((sent = write(rawsock, pkt, pkt_len)) != pkt_len)
    {
        /* Error */
        printf("Could only send %d bytes of packet of length %d\n", sent, pkt_len);
        return 0;
    }

    return 1;
  

}

struct ethhdr* CreateEthernetHeader(char *src_mac, char *dst_mac, int protocol)
{
    struct ethhdr *ethernet_header;

  
    ethernet_header = (struct ethhdr *)malloc(sizeof(struct ethhdr));

    /* copy the Src mac addr */

    memcpy(ethernet_header->h_source, (void *)ether_aton(src_mac), 6);

    /* copy the Dst mac addr */

    memcpy(ethernet_header->h_dest, (void *)ether_aton(dst_mac), 6);

    /* copy the protocol */

    ethernet_header->h_proto = htons(protocol);

    /* done ...send the header back */

    return (ethernet_header);


}

/* Ripped from Richard Stevans Book */

unsigned short ComputeChecksum(unsigned char *data, int len)
{
         long sum = 0;  /* assume 32 bit long, 16 bit short */
     unsigned short *temp = (unsigned short *)data;

         while(len > 1){
             sum += *temp++;
             if(sum & 0x80000000)   /* if high order bit set, fold */
               sum = (sum & 0xFFFF) + (sum >> 16);
             len -= 2;
         }

         if(len)       /* take care of left over byte */
             sum += (unsigned short) *((unsigned char *)temp);
        
         while(sum>>16)
             sum = (sum & 0xFFFF) + (sum >> 16);

        return ~sum;
}


struct iphdr *CreateIPHeader(/* Customize this as an exercise */)
{
    struct iphdr *ip_header;

    ip_header = (struct iphdr *)malloc(sizeof(struct iphdr));

    ip_header->version = 4;
    ip_header->ihl = (sizeof(struct iphdr))/4 ;
    ip_header->tos = 0;
    ip_header->tot_len = htons(sizeof(struct iphdr) + sizeof(struct tcphdr) + DATA_SIZE);
    ip_header->id = htons(111);
    ip_header->frag_off = 0;
    ip_header->ttl = 111;
    ip_header->protocol = IPPROTO_TCP;
    ip_header->check = 0; /* We will calculate the checksum later */
    ip_header->saddr = inet_addr(SRC_IP);
    ip_header->daddr = inet_addr(DST_IP);


    /* Calculate the IP checksum now :
       The IP Checksum is only over the IP header */

    ip_header->check = ComputeChecksum((unsigned char *)ip_header, ip_header->ihl*4);

    return (ip_header);

}

struct tcphdr *CreateTcpHeader(/* Customization Exercise */)
{
    struct tcphdr *tcp_header;

    /* Check /usr/include/linux/tcp.h for header definiation */

    tcp_header = (struct tcphdr *)malloc(sizeof(struct tcphdr));

  
    tcp_header->source = htons(SRC_PORT);
    tcp_header->dest = htons(DST_PORT);
    tcp_header->seq = htonl(111);
    tcp_header->ack_seq = htonl(111);
    tcp_header->res1 = 0;
    tcp_header->doff = (sizeof(struct tcphdr))/4;
    tcp_header->syn = 1;
    tcp_header->window = htons(100);
    tcp_header->check = 0; /* Will calculate the checksum with pseudo-header later */
    tcp_header->urg_ptr = 0;

    return (tcp_header);
}

CreatePseudoHeaderAndComputeTcpChecksum(struct tcphdr *tcp_header, struct iphdr *ip_header, unsigned char *data)
{
    /*The TCP Checksum is calculated over the PseudoHeader + TCP header +Data*/

    /* Find the size of the TCP Header + Data */
    int segment_len = ntohs(ip_header->tot_len) - ip_header->ihl*4;

    /* Total length over which TCP checksum will be computed */
    int header_len = sizeof(PseudoHeader) + segment_len;

    /* Allocate the memory */

    unsigned char *hdr = (unsigned char *)malloc(header_len);

    /* Fill in the pseudo header first */
  
    PseudoHeader *pseudo_header = (PseudoHeader *)hdr;

    pseudo_header->source_ip = ip_header->saddr;
    pseudo_header->dest_ip = ip_header->daddr;
    pseudo_header->reserved = 0;
    pseudo_header->protocol = ip_header->protocol;
    pseudo_header->tcp_length = htons(segment_len);

  
    /* Now copy TCP */

    memcpy((hdr + sizeof(PseudoHeader)), (void *)tcp_header, tcp_header->doff*4);

    /* Now copy the Data */

    memcpy((hdr + sizeof(PseudoHeader) + tcp_header->doff*4), data, DATA_SIZE);

    /* Calculate the Checksum */

    tcp_header->check = ComputeChecksum(hdr, header_len);

    /* Free the PseudoHeader */
    free(hdr);

    return ;

}

unsigned char *CreateData(int len)
{
    unsigned char *data = (unsigned char *)malloc(len);
    struct timeval tv;
    struct timezone tz;
    int counter = len;  

    /* get time of the day */
    gettimeofday(&tv, &tz);

    /* seed the random number generator */

    srand(tv.tv_sec);
  
    /* Add random data for now */

    for(counter = 0  ; counter < len; counter++)
        data[counter] = 255.0 *rand()/(RAND_MAX +1.0);

    return data;
}


/* argv[1] is the device e.g. eth0    */

main(int argc, char **argv)
{

    int raw;
    unsigned char *packet;
    struct ethhdr* ethernet_header;
    struct iphdr *ip_header;
    struct tcphdr  *tcp_header;
    unsigned char *data;
    int pkt_len;

  
    /* Create the raw socket */

    raw = CreateRawSocket(ETH_P_ALL);

    /* Bind raw socket to interface */

    BindRawSocketToInterface(argv[1], raw, ETH_P_ALL);

    /* create Ethernet header */

    ethernet_header = CreateEthernetHeader(SRC_ETHER_ADDR, DST_ETHER_ADDR, ETHERTYPE_IP);

    /* Create IP Header */

    ip_header = CreateIPHeader();

    /* Create TCP Header */

    tcp_header = CreateTcpHeader();

    /* Create Data */

    data = CreateData(DATA_SIZE);

    /* Create PseudoHeader and compute TCP Checksum  */

    CreatePseudoHeaderAndComputeTcpChecksum(tcp_header, ip_header, data);


    /* Packet length = ETH + IP header + TCP header + Data*/

    pkt_len = sizeof(struct ethhdr) + ntohs(ip_header->tot_len);

    /* Allocate memory */

    packet = (unsigned char *)malloc(pkt_len);

    /* Copy the Ethernet header first */

    memcpy(packet, ethernet_header, sizeof(struct ethhdr));

    /* Copy the IP header -- but after the ethernet header */

    memcpy((packet + sizeof(struct ethhdr)), ip_header, ip_header->ihl*4);

    /* Copy the TCP header after the IP header */

    memcpy((packet + sizeof(struct ethhdr) + ip_header->ihl*4),tcp_header, tcp_header->doff*4);
  
    /* Copy the Data after the TCP header */

    memcpy((packet + sizeof(struct ethhdr) + ip_header->ihl*4 + tcp_header->doff*4), data, DATA_SIZE);

    /* send the packet on the wire */
  
    if(!SendRawPacket(raw, packet, pkt_len))
    {
        perror("Error sending packet");
    }
    else
        printf("Packet sent successfully\n");

    /* Free the headers back to the heavenly heap */

    free(ethernet_header);
    free(ip_header);
    free(tcp_header);
    free(data);
    free(packet);

    close(raw);

    return 0;
}

Wine in Ubuntu

I like Wine application on Ubuntu a lot. It makes a significant difference between Ubuntu and Ms Windows, although not all Windows applications can be installed into Ubuntu. For some cases, it is very helpful. I suggest anybody to install and use it so that the machine becomes more flexible.
 
 
What is Wine?
Wine is a program that offers a compatibility layer allowing Linux users to run some Windows-native applications inside of Linux. Wine is not the ideal. Ideally, you should find native Linux applications. You can use Ubuntu's software package manager to search for easily installable native Linux apps, or you can explore OSalt or Linux App Finder to find alternatives for specific Windows programs.
Not all Windows applications run in Wine. And some that do require extra configuration in order to work. You may want to consult the Wine HQ app database to see if the Windows application you're thinking of installing through Wine will work well with Wine or not. Platinum-rated applications will work with no extra configuration. The example on this page is a platinum-rated application.
Installing Wine
The installation of Wine is the same as for most software. These screenshots give you a basic overview of the steps. If you're unfamiliar with how software package management works in Ubuntu, you can find more details about it here.

Using Wine

Right-click the setup.exe for the Windows program you want to install. In this case, I went to the Sumatra PDF website and downloaded the installer file called SumatraPDF-0.9.3-install.exe and right-clicked it.
In the context menu that appears, select Open with "Wine Windows Program Loader"

Do the usual next-next-next you'd normally do with a Windows program installer.

To launch the installed Windows program, go to Applications > Wine > Programs and then find the menu item for the Windows program you just installed.

The program should launch and be ready for use!
Please note
I purposely used Sumatra PDF as an example, because it is a platinum-rated Windows application, and this is just an orientation to the basics of how to use Wine. If you are planning to install a Windows program that is gold-rated, silver-rated, or bronze-rated, be prepared to do some extra configuration, and try to look for a Wine tutorial specific to that application. Or, better yet, find a native Linux alternative instead of using a Windows program.
 

Raw Sockets


Why raw sockets?

Till now we only receive frames destined to us (Unicast), everyone (Broadcast), and to a group that
we have subscribe to (Multicast).
We are only to receive only data because all the Headers i.e. Ethernet, IP, TCP etc are stripped by the network stack.
We can't modify or create a header for a packet when we send the packet.
Raw Socket is the answer to the above short comes.
With raw sockets we can get all the headers i.e. Ethernet, TCP, IP etc from the network and we can also inject packets with custom headers and data into the network directly

Promiscuous Mode

We tells the network driver to accept all packets irrespective of whom the packets are addressed to
i.e. “See All, Hear All” Wizard mode
E.g. Used for Network Monitoring
Interface can be set to promiscuous mode
         Programmatically by setting the IFF_PROMISC flag or
      •
         Using the ifconfig utility i.e. ifconfig eth0 promisc
      •
With Raw Sockets we can bypass the network stack.

Raw Socket Creation

The socket function creates a raw socket when the first argument is AF_INET/PF_INET, the second
argument is SOCK_RAW. The third argument (the protocol) is normally nonzero.
socket(PF_INET, SOCK_RAW, int protocol);
In this case A raw socket receives or sends the raw datagram not including link level headers.
                                                       (or)
The socket function can also create a raw socket when the first argument is
AF_PACKET/PF_PACKET, the second argument is SOCK_RAW. The third argument is the protocol.
socket(PF_PACKET, SOCK_RAW, int protocol)
protocol is ETH_P_IP for IP networks. It is mostly used as a filter. To receive all types of packets
ETH_P_IP is used.
In this case A raw socket receives or sends packet at layer 2 of the OSI i.e. Device driver

The Ethernet Header

Defined in linux/if_ether.h
Pictorial view
Data structure view
         struct ethhdr
         {
        unsigned char h_dest[ETH_ALEN];        /* destination eth addr */
        unsigned char h_source[ETH_ALEN]; /* source ether addr */
       unsigned short h_proto;          /* packet type ID field */
         }

The IP Header

Defined in linux/ip.h
Pictorial View
Data Structure View
         struct iphdr {
         #if defined(__LITTLE_ENDIAN_BITFIELD)
               __u8 ihl:4,
                    version:4;
         #elif defined (__BIG_ENDIAN_BITFIELD)
               __u8 version:4,
                    ihl:4;
         #else
         #error "Please fix "
         #endif
               __u8 tos;
               __u16 tot_len;
               __u16 id;
               __u16 frag_off;
               __u8 ttl;
               __u8 protocol;
               __u16 check;
               __u32 saddr;
               __u32 daddr;

Common Questions on Socket Programming

Q: Where can I get those header files?

A: If you don’t have them on your system already, you probably don’t need them. Check the manual for your
particular platform. If you’re building for Windows, you only need to #include .

Q: What do I do when bind() reports "Address already in use"?

A: You have to use setsockopt() with the SO_REUSEADDR option on the listening socket. Check out the
section on bind() and the section on select() for an example.


Q: How do I get a list of open sockets on the system?

A: Use the netstat. Check the man page for full details, but you should get some good output just typing:
$ netstat
The only trick is determining which socket is associated with which program. :-)

Q: How can I view the routing table?

A: Run the route command (in /sbin on most Linuxes) or the command netstat -r.

Q: How can I run the client and server programs if I only have one computer? Don’t I need a network to write network program?

A: Fortunately for you, virtually all machines implement a loopback network "device" that sits in the kernel
and pretends to be a network card. (This is the interface listed as "lo" in the routing table.)
Pretend you’re logged into a machine named "goat". Run the client in one window and the server in another. Or start
the server in the background ("server &") and run the client in the same window. The upshot of the loopback device
is that you can either client goat or client localhost (since "localhost" is likely defined in your /etc/hosts file)
and you’ll have the client talking to the server without a network!
In short, no changes are necessary to any of the code to make it run on a single non-networked machine! Huzzah!

Q: How can I tell if the remote side has closed connection?

A: You can tell because recv() will return 0.

Q: How do I implement a "ping" utility? What is ICMP? Where can I find out more about raw sockets andSOCK_RAW?

A: All your raw sockets questions will be answered in W. Richard Stevens’ UNIX Network Programming
books. See the books section of this guide.

Q: How do I build for Windows?

A: First, delete Windows and install Linux or BSD. };-). No, actually, just see the section on building for
Windows in the introduction.

Q: How do I build for Solaris/SunOS? I keep getting linker errors when I try to compile!

A: The linker errors happen because Sun boxes don’t automatically compile in the socket libraries. See the
section on building for Solaris/SunOS in the introduction for an example of how to do this.





Q: Why does select() keep falling out on a signal?

A: Signals tend to cause blocked system calls to return -1 with errno set to EINTR. When you set up a signal
handler with sigaction(), you can set the flag SA_RESTART, which is supposed to restart the system call
after it was interrupted.
Naturally, this doesn’t always work.
My favorite solution to this involves a goto statement. You know this irritates your professors to no end, so go for it!
select_restart:
     if ((err = select(fdmax+1, &readfds, NULL, NULL, NULL)) == -1) {
           if (errno == EINTR) {
                 // some signal just interrupted us, so restart
                 goto select_restart;
           }
           // handle the real error here:
           perror("select");
     }
Sure, you don’t need to use goto in this case; you can use other structures to control it. But I think the goto
statement is actually cleaner.
Q: How can I implement a timeout on a call to recv()?
A: Use select()! It allows you to specify a timeout parameter for socket descriptors that you’re looking to
read from. Or, you could wrap the entire functionality in a single function, like this:
#include     unistd.h
#include     sys/time.h
#include     sys/types.h
#include     sys/socket.h
int recvtimeout(int s, char *buf, int len, int timeout)
{
     fd_set fds;
     int n;
     struct timeval tv;
     // set up the file descriptor set
     FD_ZERO(&fds);
     FD_SET(s, &fds);
     // set up the struct timeval for the timeout
     tv.tv_sec = timeout;
     tv.tv_usec = 0;
     // wait until timeout or data received
     n = select(s+1, &fds, NULL, NULL, &tv);      // data must be here, so do a normal recv()
      return recv(s, buf, len, 0);
}
// Sample call to recvtimeout():
      .
      .
      n = recvtimeout(s, buf, sizeof(buf), 10); // 10 second timeout
      if (n == -1) {
            // error occurred
            perror("recvtimeout");
      }
      else if (n == -2) {
            // timeout occurred
      } else {
            // got some data in buf
      }
      .
      .
Notice that recvtimeout() returns -2 in case of a timeout. Why not return 0? Well, if you recall, a return value of
0 on a call to recv() means that the remote side closed the connection. So that return value is already spoken for,
and -1 means "error", so I chose -2 as my timeout indicator.
Q: How do I encrypt or compress the data before sending it through the socket?
A: One easy way to do encryption is to use SSL (secure sockets layer), but that’s beyond the scope of this guide.
But assuming you want to plug in or implement your own compressor or encryption system, it’s just a matter of
thinking of your data as running through a sequence of steps between both ends. Each step changes the data in some
way.
  1. server reads data from file (or whereever)
  2. server encrypts data (you add this part)
  3. server send()s encrypted data
Now the other way around:
  4. client recv()s encrypted dataYou can also do compression at the same point that you do the encryption/decryption, above. Or you could do both!
Just remember to compress before you encrypt. :)
Just as long as the client properly undoes what the server does, the data will be fine in the end no matter how many
intermediate steps you add.
So all you need to do to use my code is to find the place between where the data is read and the data is sent (using
send()) over the network, and stick some code in there that does the encryption.
Q: What is this "PF_INET" I keep seeing? Is it related to AF_INET?
A: Yes, yes it is. See the section on socket() for details.
Q: How can I write a server that accepts shell commands from a client and executes them?
A: For simplicity, lets say the client connect()s, send()s, and close()s the connection (that is, there are no
subsequent system calls without the client connecting again.)
The process the client follows is this:
  1. connect() to server
  2. send("/sbin/ls > /tmp/client.out")
  3. close() the connection
Meanwhile, the server is handling the data and executing it:
  1. accept() the connection from the client
  2. recv(str) the command string
  3. close() the connection
  4. system(str) to run the command
Beware! Having the server execute what the client says is like giving remote shell access and people can do things to
your account when they connect to the server. For instance, in the above example, what if the client sends "rm -rf
~"? It deletes everything in your account, that’s what!
So you get wise, and you prevent the client from using any except for a couple utilities that you know are safe, like
the foobar utility:
      if (!strcmp(str, "foobar")) {But you’re still unsafe, unfortunately: what if the client enters "foobar; rm -rf ~"? The safest thing to do is to write a
little routine that puts an escape ("\") character in front of all non-alphanumeric characters (including spaces, if
appropriate) in the arguments for the command.
As you can see, security is a pretty big issue when the server starts executing things the client sends.
Q: I’m sending a slew of data, but when I recv(), it only receives 536 bytes or 1460 bytes at a time. But if I run it on my local machine, it receives all the data at the same time. What’s going on?
A: You’re hitting the MTU–the maximum size the physical medium can handle. On the local machine, you’re
using the loopback device which can handle 8K or more no problem. But on ethernet, which can only handle
1500 bytes with a header, you hit that limit. Over a modem, with 576 MTU (again, with header), you hit the
even lower limit.
You have to make sure all the data is being sent, first of all. (See the sendall() function implementation for
details.) Once you’re sure of that, then you need to call recv() in a loop until all your data is read.
Read the section Son of Data Encapsulation for details on receiving complete packets of data using multiple calls to
recv().
Q: I’m on a Windows box and I don’t have the fork() system call or any kind of struct sigaction. What to do?
A: If they’re anywhere, they’ll be in POSIX libraries that may have shipped with your compiler. Since I don’t
have a Windows box, I really can’t tell you the answer, butI seem to remember that Microsoft has a POSIX
compatibility layer, and that’s where fork() would be. (And maybe even sigaction.)
Search the help that came with VC++ for "fork" or "POSIX" and see if it gives you any clues.
If that doesn’t work at all, ditch the fork()/sigaction stuff and replace it with the Win32 equivalent:
CreateProcess(). I don’t know how to use CreateProcess()–it takes a bazillion arguments, but it should be
covered in the docs that came with VC++.

          

Select()–Synchronous I/O Multiplexing

This function is somewhat strange, but it’s very useful. Take the following situation: you are a server and you want to
listen for incoming connections as well as keep reading from the connections you already have.
No problem, you say, just an accept() and a couple of recv()s. Not so fast, buster! What if you’re blocking on an
accept() call? How are you going to recv() data at the same time? "Use non-blocking sockets!" No way! You
don’t want to be a CPU hog. What, then?
select() gives you the power to monitor several sockets at the same time. It’ll tell you which ones are ready for
reading, which are ready for writing, and which sockets have raised exceptions, if you really want to know that.
Without any further ado, I’ll offer the synopsis of select():
           #include sys/time.h
           #include sys/types.h
           #include unistd.h                                                                                          int select(int numfds, fd_set *readfds, fd_set *writefds,
                          fd_set *exceptfds, struct timeval *timeout);
The function monitors "sets" of file descriptors; in particular readfds, writefds, and exceptfds. If you want
to see if you can read from standard input and some socket descriptor, sockfd, just add the file descriptors 0 and
sockfd to the set readfds. The parameter numfds should be set to the values of the highest file descriptor plus
one. In this example, it should be set to sockfd+1, since it is assuredly higher than standard input (0).
When select() returns, readfds will be modified to reflect which of the file descriptors you selected which is
ready for reading. You can test them with the macro FD_ISSET(), below.
Before progressing much further, I’ll talk about how to manipulate these sets. Each set is of the type fd_set. The
following macros operate on this type:
                               – clears a file descriptor set
• FD_ZERO(fd_set *set)
                                          – adds fd to the set
• FD_SET(int fd, fd_set *set)
                                          – removes fd from the set
• FD_CLR(int fd, fd_set *set)

                                           – tests to see if fd is in the set
• FD_ISSET(int fd, fd_set *set)
Finally, what is this weirded out struct timeval? Well, sometimes you don’t want to wait forever for someone to
send you some data. Maybe every 96 seconds you want to print "Still Going..." to the terminal even though nothing
has happened. This time structure allows you to specify a timeout period. If the time is exceeded and select() still
hasn’t found any ready file descriptors, it’ll return so you can continue processing.
The struct timeval has the follow fields:
      struct timeval {
            int tv_sec;            // seconds
            int tv_usec;           // microseconds
      };
Just set tv_sec to the number of seconds to wait, and set tv_usec to the number of microseconds to wait. Yes,
that’s microseconds, not milliseconds. There are 1,000 microseconds in a millisecond, and 1,000 milliseconds in a
second. Thus, there are 1,000,000 microseconds in a second. Why is it "usec"? The "u" is supposed to look like the
Greek letter μ (Mu) that we use for "micro". Also, when the function returns, timeout might be updated to show
the time still remaining. This depends on what flavor of Unix you’re running.
Yay! We have a microsecond resolution timer! Well, don’t count on it. Standard Unix timeslice is around 100
milliseconds, so you might have to wait that long no matter how small you set your struct timeval.
Other things of interest: If you set the fields in your struct timeval to 0, select() will timeout immediately,
effectively polling all the file descriptors in your sets. If you set the parameter timeout to NULL, it will never
timeout, and will wait until the first file descriptor is ready. Finally, if you don’t care about waiting for a certain set,
you can just set it to NULL in the call to select().
The following code snippet15 waits 2.5 seconds for something to appear on standard input:
      /*
      ** select.c - a select() demo
      */
      #include     stdio.h
      #include     sys/time.h
      #include     sys/types.h
      #include     unistd.h
      #define STDIN 0          // file descriptor for standard input
      int main(void)
      {
            struct timeval tv;
            fd_set readfds;
            tv.tv_sec = 2;
            tv.tv_usec = 500000;
            FD_ZERO(&readfds);
            FD_SET(STDIN, &readfds);
            // don’t care about writefds and exceptfds:
            select(STDIN+1, &readfds, NULL, NULL, &tv);
                                                                                                                   

            if (FD_ISSET(STDIN, &readfds))
                  printf("A key was pressed!\n");
            else
                  printf("Timed out.\n");
            return 0;
      }
If you’re on a line buffered terminal, the key you hit should be RETURN or it will time out anyway.
Now, some of you might think this is a great way to wait for data on a datagram socket–and you are right: it might
be. Some Unices can use select in this manner, and some can’t. You should see what your local man page says on the
matter if you want to attempt it.
Some Unices update the time in your struct timeval to reflect the amount of time still remaining before a
timeout. But others do not. Don’t rely on that occurring if you want to be portable. (Use gettimeofday() if you
need to track time elapsed. It’s a bummer, I know, but that’s the way it is.)
What happens if a socket in the read set closes the connection? Well, in that case, select() returns with that socket
descriptor set as "ready to read". When you actually do recv() from it, recv() will return 0. That’s how you know
the client has closed the connection.
One more note of interest about select(): if you have a socket that is listen()ing, you can check to see if there
is a new connection by putting that socket’s file descriptor in the readfds set.
And that, my friends, is a quick overview of the almighty select() function.
But, by popular demand, here is an in-depth example. Unfortunately, the difference between the dirt-simple example,
above, and this one here is significant. But have a look, then read the description that follows it.
This program16 acts like a simple multi-user chat server. Start it running in one window, then telnet to it ("telnet
hostname 9034") from multiple other windows. When you type something in one telnet session, it should appear in
all the others.
      /*
      ** selectserver.c - a cheezy multiperson chat server
      */
      #include     stdio.h
      #include     stdlib.h
      #include     string.h
      #include     unistd.h
      #include     sys/types.h
      #include     sys/socket.h
      #include     netinet/in.h
      #include     arpa/inet.h
      #define PORT 9034           // port we’re listening on
      int main(void)
      {
            fd_set master;          // master file descriptor list
            fd_set read_fds; // temp file descriptor list for select()
            struct sockaddr_in myaddr;                 // server address
                               
struct sockaddr_in remoteaddr; // client address
int fdmax;        // maximum file descriptor number
int listener;     // listening socket descriptor
int newfd;        // newly accept()ed socket descriptor
char buf[256];    // buffer for client data
int nbytes;
int yes=1;        // for setsockopt() SO_REUSEADDR, below
int addrlen;
int i, j;
FD_ZERO(&master);    // clear the master and temp sets
FD_ZERO(&read_fds);
// get the listener
if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
}
// lose the pesky "address already in use" error message
if (setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes,
                                                    sizeof(int)) == -1) {
    perror("setsockopt");
    exit(1);
}
// bind
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY;
myaddr.sin_port = htons(PORT);
memset(&(myaddr.sin_zero), ’\0’, 8);
if (bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr)) == -1) {
    perror("bind");
    exit(1);
}
// listen
if (listen(listener, 10) == -1) {
    perror("listen");
    exit(1);
}
// add the listener to the master set
FD_SET(listener, &master);
// keep track of the biggest file descriptor
fdmax = listener; // so far, it’s this one
// main loop
for(;;) {
    read_fds = master; // copy it
    if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
        perror("select");
        exit(1);
    }
                                                                                 

                 // run through the existing connections looking for data to read
                 for(i = 0; i <= fdmax; i++) {
                       if (FD_ISSET(i, &read_fds)) { // we got one!!
                            if (i == listener) {
                                  // handle new connections
                                  addrlen = sizeof(remoteaddr);
                                  if ((newfd = accept(listener, (struct sockaddr *)&remoteaddr,
                                                                                            &addrlen)) == -1) {
                                       perror("accept");
                                  } else {
                                       FD_SET(newfd, &master); // add to master set
                                       if (newfd > fdmax) {             // keep track of the maximum
                                             fdmax = newfd;
                                       }
                                       printf("selectserver: new connection from %s on "
                                             "socket %d\n", inet_ntoa(remoteaddr.sin_addr), newfd);
                                  }
                            } else {
                                  // handle data from a client
                                  if ((nbytes = recv(i, buf, sizeof(buf), 0)) <= 0) {
                                       // got error or connection closed by client
                                       if (nbytes == 0) {
                                             // connection closed
                                             printf("selectserver: socket %d hung up\n", i);
                                       } else {
                                             perror("recv");
                                       }
                                       close(i); // bye!
                                       FD_CLR(i, &master); // remove from master set
                                  } else {
                                       // we got some data from a client
                                       for(j = 0; j <= fdmax; j++) {
                                             // send to everyone!
                                             if (FD_ISSET(j, &master)) {
                                                  // except the listener and ourselves
                                                  if (j != listener && j != i) {
                                                        if (send(j, buf, nbytes, 0) == -1) {
                                                             perror("send");
                                                        }
                                                  }
                                             }
                                       }
                                  }
                            } // it’s SO UGLY!
                       }
                 }
           }
           return 0;
     }
Notice I have two file descriptor sets in the code: master and read_fds. The first, master, holds all the socket
descriptors that are currently connected, as well as the socket descriptor that is listening for new connections.

                                                                             
The reason I have the master set is that select() actually changes the set you pass into it to reflect which sockets
are ready to read. Since I have to keep track of the connections from one call of select() to the next, I must store
these safely away somewhere. At the last minute, I copy the master into the read_fds, and then call select().
But doesn’t this mean that every time I get a new connection, I have to add it to the master set? Yup! And every
time a connection closes, I have to remove it from the master set? Yes, it does.
Notice I check to see when the listener socket is ready to read. When it is, it means I have a new connection
pending, and I accept() it and add it to the master set. Similarly, when a client connection is ready to read, and
recv() returns 0, I know the client has closed the connection, and I must remove it from the master set.
If the client recv() returns non-zero, though, I know some data has been received. So I get it, and then go through
the master list and send that data to all the rest of the connected clients.
And that, my friends, is a less-than-simple overview of the almighty select() function.