Showing posts with label windows. Show all posts
Showing posts with label windows. Show all posts

Friday, 15 August 2014

SOCKET PROGRAMMING

Generally a socket is an endpoint communication between two systems on a network.
A socket address is a combination of IP address and Port number.
Sockets are bi-directional.
The application that initiates the communication is called a Client and the other one is called Server.

TYPES OF SOCKETS:

1. Socket Stream- connection oriented,(i.e)the first the two parties establish a connection after which any data is passed through that connection.
2. Datagram Socket- connection less(i.e) either party sends datagrams as neede and waits for the other to respond.

PROTOCOL: 

1. Initialize Winsock in the server
2. create a socket for the server
3. bind the socket-Connection
4. listen on the socket for the client
5. Now,Initialize the winsock for the Client
6. Create a socket for the Client
7. Connect to the server 
8. Server must accept the connection from the client
9. send and receive data 
10. Disconnect the chat

SERVER SIDE

          1)Initialize Winsock in the server-Create a WSADATA object called wsaData.
                        
                WSADATA wsaData; -->The WSADATA structure contains information about the Windows Sockets implementation.
    
          2) Call WSAStartup and return its value as an integer and check for errors.The WSAStartup function is called to initiate use of WS2_32.dll.
             The WSADATA structure contains information about the Windows Sockets implementation. 
             The MAKEWORD(2,2) parameter of WSAStartup makes a request for version 2.2 of Winsock on the system,
             and sets the passed version as the highest version of Windows Sockets support that the caller can use.

              Result = WSAStartup(Version, &wsaData);             
              if (Result != ZERO)
     {
               printf("WSAStartup failed with error\n");
  free(sendbuf);
                   return 1;
              }  
       else 
     {
  printf("WSAStartup success\n");
     }

                     
3) After initialization, a SOCKET object must be instantiated for use by the client.
           Declare an addrinfo object that contains a sockaddr structure and initialize these values.
           For this application, the Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned. 
           The application requests the socket type to be a stream socket for the TCP protocol.
                               

    struct addrinfo *result;
              struct addrinfo hints;

              memset(&hints, 0, sizeof(hints)); // making hints to zero
              hints.ai_family = AF_INET; // address family formats for IPv4
              hints.ai_socktype = SOCK_STREAM; // sock-stream,(reliable two way communication)
              hints.ai_protocol = IPPROTO_TCP;        // Transmission Control Protocol (TCP)
     hints.ai_flags = AI_PASSIVE; // the caller intends to use the returned socket address structure in a call to the bind function
             
         4) Call the getaddrinfo function requesting the IP address for the server name passed on the command line. 
            The TCP port on the server that the client will connect to is defined by DEFAULT_PORT as 27015 in this sample.
            The getaddrinfo function returns its value as an integer that is checked for errors. 


               Result = getaddrinfo(HOST_ADDRESS, DEFAULT_PORT, &hints, &result); // hold the address info
               if (Result != ZERO)
      {
                  printf("getaddrinfo failed\n");
 free(sendbuf);
                  return 1;
               }
     else
      {
printf("getaddrinfo success\n");
      }


5)  Create a SOCKET object called ConnectSocket.Call the socket function and return its value to the ConnectSocket variable. For this application,
            use the first IP address returned by the call to getaddrinfo that matched the address family, socket type, and protocol specified in the hints parameter.
            In this example, a TCP stream socket was specified with a socket type of SOCK_STREAM and a protocol of IPPROTO_TCP. 
            The address family was left unspecified (AF_UNSPEC), so the returned IP address could be either an IPv6 or IPv4 address for the server.
            If the client application wants to connect using only IPv6 or IPv4, then the address family needs to be set to AF_INET6 for IPv6 or AF_INET for IPv4 in the hints parameter.


ListenSocket = socket(result->ai_family,result->ai_socktype,result->ai_protocol); // Create a SOCKET to listen
                if (ListenSocket == INVALID_SOCKET)
       {
                   printf("socket not Created\n");
                   free(sendbuf);
                   return 1;
                }
       else
       {
  printf("Socket Created\n");
       }

        6)  Bind the socket

                Result = bind( ListenSocket, result->ai_addr, result->ai_addrlen); // Setup the TCP listening socket
                if (Result != ZERO)
       {
                    printf("bind failed\n");
                    free(sendbuf);
                    closesocket(ListenSocket);
                    return 1;
                }
       else
       {
    printf("bind success\n");
       }         
   

       7) Call the listen function, passing as parameters the created socket and a value for the backlog,
          maximum length of the queue of pending connections to accept.
          In this example, the backlog parameter was set to SOMAXCONN. 
          This value is a special constant that instructs the Winsock provider for this socket to allow a maximum reasonable number of pending connections in the queue.
          Check the return value for general errors.


Result = listen(ListenSocket,0);            // listening on the socket for the client
                if (Result != ZERO) 
       {
                   printf("listen failed\n");
  free(sendbuf);
                   closesocket(ListenSocket);
                   return 1;
                }
       else 
       {
  printf("Listen success\n");
       }

      8) Once the socket is listening for a connection, the program must handle connection requests on that socket.
         Create a temporary SOCKET object called ClientSocket for accepting connections from clients.


              ClientSocket = accept(ListenSocket, NULL, NULL);    // Accept a client socket
              if (ClientSocket == INVALID_SOCKET)
     {
                printf("accept failed\n");
free(sendbuf);
                closesocket(ListenSocket);
                return 1;
              }
     else
     {
printf("Accept success\n");
     }

      

CLIENT SIDE

    1) Similarly initialize winsock,like you did in server.After initialization, a SOCKET object must be instantiated for use by the client.
       create a socket.Declare an addrinfo object that contains a sockaddr structure and initialize these values.
       For this application, the Internet address family is unspecified so that either an IPv6 or IPv4 address can be returned. 
       The application requests the socket type to be a stream socket for the TCP protocol.


        WSADATA wsaData;                                  
                 Result = WSAStartup(Version, &wsaData); // Initialize Winsock
                 if (Result != 0)
        {
                    printf("WSAStartup failed\n");
   free(sendbuf);
                    return 1;
                 }
        else
        {
   printf("WSAStartup success\n");
        }

                struct addrinfo *result;                           
                struct addrinfo hints;                              

                memset(&hints, 0, sizeof(hints));        // making hints to zero
                hints.ai_family = AF_INET;       // address family formats for IPv4
                hints.ai_socktype = SOCK_STREAM;     // sock-stream,(reliable two way communication)
                hints.ai_protocol = IPPROTO_TCP;      // Transmission Control Protocol (TCP)


2) Call the getaddrinfo function requesting the IP address for the server name passed on the command line.
           The TCP port on the server that the client will connect to is defined by DEFAULT_PORT as 27015 in this sample. 
           The getaddrinfo function returns its value as an integer that is checked for errors.

                 Result = getaddrinfo(LOOP_ADDRESS,DEFAULT_PORT, &hints, &result);         // hold address information
                 if (Result != 0)  
        {
                     printf("getaddrinfo failed\n");
    free(sendbuf);                            
                     return 1;
                 }
        else
       {
    printf("getaddrinfo success\n");
       }

3) Call the socket function and return its value to the ConnectSocket variable.
           For this application, use the first IP address returned by the call to getaddrinfo that matched the address family, socket type, and protocol specified in the hints parameter.
           In this example, a TCP stream socket was specified with a socket type of SOCK_STREAM and a protocol of IPPROTO_TCP.The address family was left unspecified (AF_UNSPEC), 
           so the returned IP address could be either an IPv6 or IPv4 address for the server.If the client application wants to connect using only IPv6 or IPv4, 
           then the address family needs to be set to AF_INET6 for IPv6 or AF_INET for IPv4 in the hints parameter.


ConnectSocket=socket(result->ai_family,result->ai_socktype,result->ai_protocol); // Creating a SOCKET with necessary parameters
                if (ConnectSocket == INVALID_SOCKET)
       {
                   printf("socket creation failed\n");
  free(sendbuf);
                   return 1;
                }
       else
       {
  printf("socket created\n");
       }

4) Call the connect function, passing the created socket and the sockaddr structure as parameters. Check for general errors.

Result = connect(ConnectSocket, result->ai_addr,result->ai_addrlen);    // Connect to server
                         if(Result != ZERO)
                {
                           printf("Unable to connect to server!\n");
         _getch();
          closesocket(ConnectSocket);                                        // closing the created socket
          free(sendbuf);
          return 1;
                }
                           printf("server connected\n");



THAT'S ALL NOW HERE IS THE SNIPPET FOR SENDING AND RECEIVING-COMMON FOR BOTH

        printf("\n*** For Disconnecting the Chat don't type anything,just simply press 'ENTER' ***\n"); 
while(1)
{
printf("\nCLIENT: ");
fflush(stdin);     // clear the stdin buffer
gets(sendbuf); 
int string_len=strlen(sendbuf);
Send_Result = send(ConnectSocket,sendbuf,string_len,0);        
if(Send_Result==0)
{
break;
}
Recv_Result = recv(ConnectSocket,recvbuf,MAX_LEN,0);
if(Recv_Result==0)
{
break;
}
recvbuf[Recv_Result]='\0';                                          // appending a null character
printf("\nSERVER: %s\n",recvbuf);
}
free(sendbuf);
closesocket(ConnectSocket);   
return 0;
}
NOTE:the IP is LOOP BACK 127.0.0.1 if you r running it on the same computer


OUTPUTS:

---->>1st run the server





----->client is trying to connect





NOW the client is connected you can chat



Author
Aravind A
Project Engineer

   

Thursday, 24 July 2014

How to Capture “Friendly Name” from a Camera

Hi, Today am back with a mindblowing,method to tell you how you can capture or get a Friendly name of a camera.

What is a Friendly Name??
Any devices, will have some kind of ID for identification, some of them are
Device ID:
Vendor ID: etc...
Since all these are numbers, it is hard to be remembered by the user, so therefore a short name to recognize the type of camera , is called the friendly name.

Ex:USB 2.0

Things Required:
1.Visual Studio
2.Platform SDK
3.A Camera
So lets get started,into our journey of capturing Friendly names of a camera

STEP 1:
Install,the platform SDK,properly.You can have a look into my previous chapters where I would have discussed that.

STEP 2:
Open Visual Studio 2005, and then open a new Win32 Project,hope you are familiar with building Win32 Apps.For those who are not, dont worry, in a week or so I will post tutorials on win32 programming

STEP 3:
Just make a simple dialog box with an button,add a list box for viewing the enumerated Device. Just see the screen shot  below.
                                
STEP 4:
This is a crucial step as I am going do  a brief explanation of some of the concepts. I have commented my program ,to an extend where you can easily understand.

Here We are going to use a concept called COM(Component Object Model) which is a binary interface standard for software modules. It’s an interface between two program modules, one of them is an OS or a library.

System Device Enumerator
It returns a collection of device Monikers, selected by a device category.It enumerates Filters and hardware installed on the system.

Monikers
It contains information that uniquely identifies a component object model.
There is two important properties of it
1. Can be saved and later retrieved.
2. Support an operation called binding, which is a process of locating object named by a Moniker, activating and loading it, if it is not already active.

Iproperty Bag
This is a kind of variable ,or you can assume it as a bag as the name suggests, from which we can read the values. The Imonikers saves the object properties on it.
  Just see the program ,try building it and running it and then explore your own ideas with it.

If all step is  properly done then you can see an  window , as shown below


And here we come to the end of this tutorial ,hope you liked it.
Author
Vivek Gr
Embedded Project Engineeer




Thursday, 17 July 2014

USB EVENT TRACING - WINDOWS MESSAGE ANALYZER

WINDOWS MESSAGE ANALYZER:

INTRODUCTION

Windows Message Analyzer is a free tool provided by Microsoft which has combined capablities of event tracing and viewing the trace under one user interface. It is simpler to analyze USB event traces in Windows Message Analyzer.
In the previous method .etl generation is done separately using logman tool and .etl viewing is done separately through event viewer or network monitor or any other tools. So message analyzer combines these discrete steps into a single window and makes the process simpler. You can also use export option to view the same trace using network monitor as well if in case netmon is your prefered trace viewer.

DOWNLOADING WINDOWS MESSAGE ANALYZER

Follow this link Windows message analyzer download to download. The installation process is simple.

STEPS FOR USB TRACING

  • Open the Windows message analyzer and select 'capture/trace' option from the left pane.
  • From the 'trace scenarios' column we can select either USB 2.0 or USB 3.0.

  • As already known USB 3.0 tracing support (for XHCI) will only be provided by windows 8+ pc which has necessary trace providers.
  • Select the necessary trace providers from the list in 'trace scenario configuration' pane.
  • We can select the filter parameters for the particular trace provider using message type(information, error etc.) and keywords (parameters available for particular trace provider) from box below the trace scenario configuration pane.
  • Filters can also be added before starting an event trace in the 'trace filter' pane.
  • After all these configurations are complete, 'start with' button can be pressed to start the trace.
  • After starting the trace a new window with all trace information will open.

  • Restart, stop, pause options are available and can be used according to necessities.
  • There is also a filter option in this window which can be used to filter traced data.
  • Each and every message can be expanded to view the field data which contains the information about data packets and stack data which contains the event id, process id etc.
  • After finishing the tracing part, we can save it for future reference as .matp file for viewing it in message analyzer.
  • If you wish to view a particular trace using any other tools like netmon, export option should be used which saves the traced file as .cap.

TWO METHODS OF FILTERING

  • Right click button can be best utilized for filtering a trace according to particular parameters.
  • Right click can be used in any of the columns of the message window separately or inside the field and stack data.

COLUMN FILTERING

A rightclick in any one of the columns will filter according to data in that column. We can also add columns of our choice and then add a filter with the column data available. For example, we can add a column call usb device and filter messages from a particular usb device connected.



FIELD OR STACK FILTERING

A right click in any data on field or stack information will add the corresponding filter to the view filter box.



Comment and criticize our mistakes !!

-ARUN
Embedded Engineer