Tuesday 27 November 2012

How To Tag Source

The following are the steps which will be useful to tag the source,

1. Go to your root directory of source bed
  Ex: cd /app/src/main_src/

 2. execute ctags -R
  if it is not working
 do which ctags , get the path of it and then execute by following ,
ex:
/usr/bin/ctags -R

3. now you could see  file "tags" created in your root src dir
4. now set tags for your vim

 open your vimrc file

vi ~/.vimrc
set tags=/app/src/main_src/tags

:wq

5. from now where ever your are in your src, you can get the func definition by "ctrl + ]" to get back "ctrl + t"

Enjoy the tagging ..!!

Let me know in case of  help required ..



Thursday 18 October 2012

How to install Klocwork in linux


*****************How to Install Klocwork in Local Server?*********************************

1) Create a user and group (klocwork/klocwork123)
2) Login into the machine using above user and password.
3) create a directory klocwork_9.2 (mkdir klocwork_9.2)
4) Copy kw-server-installer.9.2.1.7276.linux.sh to klocwork_9.2 folder.
5) chmod 755 *.sh
6) Create kwtables, kw92 and kwdata directory in klocwork_9.2 folder(eg : mkdir kw82 kwdata)
7) Run kw-server-installer.9.2.1.7276.linux.sh
(eg: ./kw-server-installer.9.2.1.7276.linux.sh -a -i /home/klocwork/klocwork_9.2/kw92/ -p /home/klocwork/klocwork_9.2/kwdata/
8) open bashrc and export klocwork binary paths.
(eg: export PATH=$PATH:/home/klocwork/klocwork_9.2/kw92/bin/)
9) save bashrc file and run it( source ~/.bashrc)
10) kwservice set-service-property <path to kwdata> license host <license machine ip address>
(eg: ./kwservice set-service-property /home/klocwork/klocwork_9.2/kwdata/ license host 172.16.1.151
11) cd ..
12)chmod 755 *.sh
13) Install kw-user-installer.9.2.1.7276.linux.sh
(eg:./kw-user-installer.9.2.1.7276.linux.sh /home/klocwork/klocwork_9.2_Client/)
14) Enter then type Yes again Enter
15) After Installation is over open .bashrc and add client bin path
(eg:/home/klocwork/klocwork_9.2_Client_New/bin/)
****now your export path is :export PATH=$PATH:/home/klocwork/Klocwork9.2/kw92/bin/:/home/klocwork/klocwork_9.2_Client_New/bin/
16) save bashrc and run (source .bashrc)
17) Go to kwdata/config folder (eg :/home/klocwork/Klocwork9.2/kwdata/config)
18) Open admin.conf file
19) Change project.host , project.java.rmi.server.hostname , web.host, database.host as Ip address of Klockwork installing machine.
20) If project.java.rmi.server.hostname is not present in admin.conf add it ( *its not mandatory)
21) Change license.host = IP Address of License Server.(172.16.1.151)
22) If Required change web port .
23) Save the admin.conf
24) kwservice start <path to kwdata>
(eg: kwservice start /home/klocwork/klocwork_9.2/kwdata/ )
25) Now License Server, Database Server , Project Server and Web Server should start.
    Change the port-adress of database.port to some other port if  default 3306 is used by default mysql already installed in the system.
    Webserver is the klocserver.
    project server is the project_root installed in the machine.
   
26) If databse /project/web server is not starting check these ports are already using or not ?
****if is its using change the port and start again.
27) if any problem for starting License server contact klocwork admin
28) open gui http://ipaddressof klocwork installed machine:webport
(eg:http://172.19.1.61:8072)
29) open gui in another way also go to <path of kw92/bin> ./kmc
(eg:/home/klocwork/klocwork_9.2/kw92/bin)
****before starting kmc install cigwin or any other tool

*****************To work with KlocWork*********************


Once the installation is done now to work with the code fallow the fallowing procedure.


1)Go to the sourcecode folder, here we need to generate build specification file. Use the fallowing command
to generate build.spec file
    kwinject -o build.spec make
    The above command uses make file in the source code folder and complies and generates specification file.
    Dont forget to do make clean before to do make.
2)Run KMC in command window using command kmc. This will invoke a GUI tool where we can create project and build it.
3)To create project, go to file->New project, Name the project and select the language  click next.

4) In the next window select Build From Build Specification files click add, browse for the build specification file that you have done in step 1.

5)Click Next.
6)Select the options in the next window and click finish.
7)On the left side of the UI you will project list, right click on your project click on build. This step intiates building of recent build version.

8)UI will asks for KlocWorks Tables Directory, Select  Reuse Tables Directory and browse for the tables directory path /home/klocwork/klocwork_9.2/kwtables/ and click build.

9)Your code starts building and the process will take some time. After completion of successful build you can see the reports on the browser.

10)Open the browser with klocServer ip addess (ex: http://172.19.3.178:8080) and select Klocwork Review. UI asks username and password. username is admin and no password.

11)UI will load the complete list of projects, select your coressponding project to view reports.






How To Configure Yum in Linux

cat /etc/yum.repos.d/local.repo
[localrepos]
name=Local Repository
baseurl=file://///mnt/disk
enabled=1
gpgcheck=0

#Here consider that RHEL ISO file being mounted in /mnt/disk directory

#Either we can mount using NFS too to configure Yum Path

Command to mount ISO file in linux

mount -o loop file.iso /mnt/disk


Monday 15 October 2012

IPV6 How it works

IPV6 Connection happening on the local machine, but not connecting from the LAN. What may be the cause?
1. Check does assigned IPV6 has route to reach LAN
2. Check the status firewall (ip6tables in case of IPV6 network)
3. If Firewall running on local machine , stop firewall or modify accordingly to reach out LAN from local machine
How to stop firewall for IPV6 network, following
service ip6tables stop
4. how to check route for ipv6
ip -6 route


Information about IPV6


1. Enables Innovation , for application without NAT
2. IPV6 Address represented by hexa decimal numbers
3. There is no netmask in IPV6, it has only prefix length
4. IPV6 headers are 40bytes long, header doesn't include checksum, so if designing software, UDP checksum is mandatory
5. There is no broadcast in IPV6, it has only Multicasting
6. In IPV6 there is no ARP or IGMP, ICMP6 takes those jobs
7 .There are different types of IPV6 Addresses, they are Unicast, Multicast, Anycast, Reserved
8. There are also different scopes for IPV6, they are Local, Link, Global

IPV6 continuation
Lets go in detail, about the difference in IPV4/6 ..

how IPV6 really differs from IPV4 ..

IPV4 has several class of IP Addressing

IPV6 addressing follows,

As we know IPV6 has 128 bits wide,

starting from MSB, first 64 bits for network id, next 64 bits for host id

Here in host identifier can also be called as interface identifier.

In case of IPV4, a single interface can hold only a single IP Address ..

For example:
eth0 - can hold single unique IP Address
say 172.19.12.51

In IPV6 there are different scope defined for the interfaces.

Means a single interface can hold multiple IP's too, which overcomes IPV4 drawback ..

lets go interface wise ..

yes IPV6 has loop back address namely. ::1/128

lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:933651 errors:0 dropped:0 overruns:0 frame:0
TX packets:933651 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:204721069 (195.2 MiB) TX bytes:204721069 (195.2 MiB)


Here we could see the scope of the loopback interface (lo), which is Scope: Host

Here the convension differs from IPV4, i.e successive leading zero's can be combined, not trailing zero's

A IPV6 address can hold only single combined successive leading zeros

For Example:

IPV6 Address : 2001:0DB8:130F:0000:0000:7000:0000:140B can be called by following,

2001:DB8:130F:0:0:7000:0:140B(Leading zeroes)

2001:DB8:130F:0:0:7000:0:140B(Trailing zeroes)

2001:DB8:130F::7000:0:140B(Successive field of zeroes)

Hene we can combine successive leading zeros, not trailing zeros.

Also there is only one time successive leading zeros can be combined in a given IPV6 Address.


Following are IPV6 addressing types.

1. Unicast
2. Multicast
3. Anycast

Note that IPV6 doesn't have broadcasting in nature.

There are different other scopes are available those are used for different purposes,
they are,

1. Link Local -- peer-to-peer communication (starts with FE80::) -- not intended to route
2. Unique Local -- starts with FD00:: -- within domain
3. Site Local -- intended to use within the site ( similar to unique local )
4. Global Unique -- global unique IPV6 address, can be routable ( similar to public IP Address in case of IPV4)



Is there a default DHCP address segment in IPv6 (similar to 169.254.x.x series in IPv4) ?
yes, it has fe80::/64 prefix .

In general IP Address can be assigned by following ways,

1. Configure Manually
2. Assign Dynamically with help of DHCP configured, IP Address can be assigned by DHCP for lease, will expire after certain time interval , otherwise DHCP can assign permanently . Again it depends on DHCP Server configuration
3. Assigning IP Address (local link) using default address block 169.254.0.0/16 for ipv4, In IPv6, they are assigned with the fe80::/64 prefix.

In IPV6 most often local link address will be assigned using stateless address autoconfiguration.



How many bits are present in an IPv6 address ?

There are 128 bits (16 bytes/octets) in an IPv6 address.  Please note that the "6" in IPv6 refers to IP specification version/release 6 and not the number of bytes in the address.  It so happens that in IPv4, the number of bytes in the address is 4.




How is loopback address represented in IPv6 ?
Its represented as ::1/128

In IPv6 the loopback address is a single IP address and hence the netmask bit of 128 above.

In the long form its
0000:0000:0000:0000:0000:0000:0000:0001/128

A slightly shorter from is
0:0:0:0:0:0:0:1/128

The shortest and usual form is
::1/128

Considering the IP alone its
::1

Note: In IPv4 the loopback address is 127.0.0.1/8



How many bits are present in an IPv6 address ?
128 bits.


How many bits are present in an IPv6 address ?
128 bits.
128/8=16 bytes

Neighbor Discovery Protocol (stateless auto configuration -- replacement of DHCP, ARP)
===========================================================
Here assume that N number of hosts are connected with Router
H1---
H2----
H3----ROUTER
.
.
.
Hn----

how link local unique address assigned

Steps are following,

As per understanding of IPV6 Address, first 64bit are meant for Network ID rest 64bit meant for HostID/Interface ID

To Generate unique link local IPV6 Address,
1. First 10 bits always will be 1111 1110 10 --> meant for link local address  rest 54 bits will be zero
   In terms it will be fe80:: (leading zeros are combined, not trailing zeros)
   The next 64bit interface id will be generated based on MAC address of the client system
  
   Assume that interface ID being generated by MAC address,
   And the IPV6 link address is fe80::219:d1ff:fe97:768c/64
  
 2. Now the second step, how the client has to make sure that there is no one in this network using this link local address
    This can be achieved by Neighbor Discovery Protocol underline with help of newly designed ICMP6
   
    How to test assigned link local address is unique
   
    a. Send Neighbor Solicitation and listen for Neighbor advertisement --> it means that IP Address is in use -> if not then goahead with router contact
    b.The node next attempts to contact a local router for more information on continuing the configuration.
      This is done either by listening for Router Advertisement messages sent periodically by routers,
      or by sending a specific Router Solicitation to ask a router for information on what to do next
      The router provides direction to the node on how to proceed with the autoconfiguration.
      It may tell the node that on this network “stateful” autoconfiguration is in use,
      and tell it the address of a DHCP server to use. Alternately, it will tell the host how to determine its global Internet address.
    c. Global Address Configuration: Assuming that stateless autoconfiguration is in use on the network,
      the host will configure itself with its globally-unique Internet address.
      This address is generally formed from a network prefix provided to the host by the router,
      combined with the device's identifier as generated in the first step
     
     

How MAC Table updated in IPV6:
=====================

Following is the command to get mac table entry in linux

 ip -6 neigh list

Following are the steps which will help kernel to update MAC entry for IPV6

1. Assume that there is no entry for say ip1 host , and ip1 is belonging to your network ( means it is reachable from your client)
2. Consider you have been assigned with some link local address and you want to reach/ping some one who is sitting in your network ex: ip1
 3.  Ideally the client should know the MAC address of other peer to establish communication,

 in this case when you do ping6 ip1 , client sends multicast request to ff02::1:ff:(24 least bits of your ip1 ) -- neighbor solicitation follows under icmpv6

therefore ip1 will reply back  with ip1 MAC address follows neighbor solicitation under icmpv6

 This is the stage client will do neighbor advertisement,  means client updated MAC table entry

then actual ping request will be sending to ip1, and vise versa.





 



Thursday 11 October 2012

TCP Track Connections

http://pkgs.repoforge.org/tcptrack/tcptrack-1.4.0-1.el6.rf.x86_64.rpm

rpm -ivh tcptrack-1.4.0-1.el6.rf.x86_64.rpm

 tcptrack -i eth0

tcptrack -i eth0 src or dst 76.11.22.12
 tcptrack -i eth1 port 80

This is interesting tool which help us to track the connection between the peers 



How to disable storing svn password for all users

vi ~/.subversion/config

[auth]
## Add below lines under this section auth

store-auth-creds = no
store-passwords = no

--------------------

have a look if there are some files under this directory
~/.subversion/auth/svn.simple/
if so delete the files , those files called password cached files.

---------------------

Try now, it will prompt you to enter password

let me know in case of help required

Wednesday 26 September 2012

how to debug segfault from /var/log/message kenel message

Scenario:

Core is not enabled, before program executes, and there was a crash happened , which has logged into /var/log/message

Also make sure that abrtd service stopped.

In case of abrtd service running abrtd ( abort daemon) will not dump a core file nor write error segfault message in /var/log/message.

instantly once application crashed abort daemon will dump a core under /var/spool/abrt/ , upon identifies program is not part of default package/module of system, it will delete dumped core file .

Hence make sure that abort daemon is not running on your system.

There are some cases even if you enable core, if the core file size is  exceeds allowable limit, you may not able to find proper info when you debugging with gdb.

Coming to our discussion,

How to debug a program/process which crashed, and has logged message in /var/log/message

Consider that you have message like this in your /var/log/message

Sep 27 11:25:12 MDP-204 kernel: a.out[4302]: segfault at 0 ip 000000000040047c sp 00007fff3cdf9060 error 6 in a.out[400000+1000]

ip --> instruction pointer
sp --> stack pointer
error 6 --> no address ( means possible crash due to this error no 6)
a.out[400000+1000] --> a.out (program name) base address + virtual memory taken while loading program

hence instruction pointer should be within this range  40000 : 401000

here my test program crashed due to there is no address to store value.

how to get location, using command called "addr2line"

<addr2line> -e <exe name> <instruction pointer addr>
#addr2line -e a.out 000000000040047c
debug.c:7
#

sample program follows,

debug.c

#include <stdio.h>

int main()
{
        char *ptr;

        *ptr = 'a'; //program will crash here

        return 0;
}


Therefore we got useful information that in test program debug.c line number 7 is caused crash.

let me know if anyone has alternative methods for this scenario.


Apart from addr2line, we can use nm, objdump to debug the program

in the above same test program case

generate objdump

#objdump -DCl <exe-name>  > obj.out  -- search instruction pointer in this object file

its also hard, if you are not aware of assembly language , since we would need to map from assembly code into actual source code .. , more over its again depends on the debugging symbols options

 i  always recommend build your program with debug option, ex: gcc -g3 O2 -Wall test.c

Hopefully we could able to get some info from objdump at the final.

#another command objdump --architecture -d <exec-file>   -- this will also help  to find root caused


HowTo Shared Library in Linux

Library Name : hello

filename : hello.c

#include <stdio.h>

void Hello()
{
  printf("Hello World .. How are you 1\n");
}
======================================
Header File:

hello.h

#ifndef __HELLO_H
#define __HELLO_H

void Hello(void);

#endif

===============================

Application :

filename : app.c

#include <stdio.h>
#include "hello.h"

int main()
{

  Hello();

  return 0;
}

====================================

Makefile:

VERSION = 1
MINORVER = 1
RELEASEVER = 1

LIBNAME = libhello
DYLIBSUFFIX = so

SONAME = $(LIBNAME).$(DYLIBSUFFIX).$(VERSION)
REALNAME = $(SONAME).$(MINORVER).$(RELEASEVER)

MAJORNAME = $(SONAME)
DYLIBNAME = $(LIBNAME).$(DYLIBSUFFIX)


OBJS = hello.o

all: $(LIBNAME)

$(LIBNAME): $(OBJS)
  $(CC) -shared -Wl,-soname,$(SONAME) -o $(REALNAME) $(OBJS)
  ln -sf $(REALNAME) $(MAJORNAME) && ln -sf $(MAJORNAME) $(DYLIBNAME)

hello.o: hello.c
  $(CC) -fPIC -c -g -Wall hello.c

app: app.o
  $(CC) -o $@ app.o -L./ -lhello

clean:
  -@rm *.o

distclean:  clean
  -@rm libhello.so* app




Monday 3 September 2012

SCP/SSH without entering password

1. Generate public key at local host
follows,

[root@hp6core1 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
e6:46:ca:ee:10:25:1f:7c:3f:25:de:24:3d:c2:6a:20 root@hp6core1
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|     .   . .     |
|    E = . = =    |
|     = + + B .   |
|    . . S + .    |
|     o *   .     |
|    . o o        |
|     o .         |
|     .o          |
+-----------------+

2. copy pub file to remote host , follows as
[root@hp6core1 ~]# scp /root/.ssh/id_rsa.pub remoet-host:/root/.ssh/authorized_keys

3. Otherwise append the content into authorized keys at remote file in case file exists

Saturday 1 September 2012

IPV6 Simple Server Program

/**************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define SERVER_PORT     3005
#define BUFFER_LENGTH    250
#define FALSE              0

void main()
{
                int sd=-1, sdconn=-1;
                int rc, on=1, rcdsize=BUFFER_LENGTH;
                char buffer[BUFFER_LENGTH];
                struct sockaddr_in6 serveraddr, clientaddr;
                int addrlen=sizeof(clientaddr);
                char str[INET6_ADDRSTRLEN];

                do
                {
                                if ((sd = socket(AF_INET6, SOCK_STREAM, 0)) < 0)
                                {
                                                perror("socket() failed");
                                                break;
                                }

                                if (setsockopt(sd, SOL_SOCKET, SO_REUSEADDR,
                                                                                (char *)&on,sizeof(on)) < 0)
                                {
                                                perror("setsockopt(SO_REUSEADDR) failed");
                                                break;
                                }

                                memset(&serveraddr, 0, sizeof(serveraddr));
                                serveraddr.sin6_family = AF_INET6;
                                serveraddr.sin6_port   = htons(SERVER_PORT);

                                serveraddr.sin6_addr   = in6addr_any;
  if (bind(sd,
                                                                                (struct sockaddr *)&serveraddr,
                                                                                sizeof(serveraddr)) < 0)
                                {
                                                perror("bind() failed");
                                                break;
                                }

                                if (listen(sd, 128) < 0)
                                {
                                                perror("listen() failed");
                                                break;
                                }

                                printf("Ready for client connect().\n");

                                addrlen=sizeof(clientaddr);
                                if ((sdconn = accept(sd, (struct sockaddr *)&clientaddr, &addrlen)) < 0)
                                {
                                                perror("accept() failed");
                                                break;
                                }
                                else
                                {
                                                //getpeername(sdconn, (struct sockaddr *)&clientaddr, &addrlen);
                                                if(inet_ntop(AF_INET6, &clientaddr.sin6_addr, str, sizeof(str))) {
                                                                printf("Client address is %s\n", str);
                                                                printf("Client IP Family [%d]\n", clientaddr.sin6_family);
                                                                printf("Client port is %d\n", ntohs(clientaddr.sin6_port));
                                                }
                                }

                                /********************************************************************/
                                /* In this example we know that the client will send 250 bytes of   */
                                /* data over.  Knowing this, we can use the SO_RCVLOWAT socket      */
                                /* option and specify that we don't want our recv() to wake up      */
                                /* until all 250 bytes of data have arrived.                        */
                                /********************************************************************/
                                if (setsockopt(sdconn, SOL_SOCKET, SO_RCVLOWAT,
                                                                                (char *)&rcdsize,sizeof(rcdsize)) < 0)
                                {
                                                perror("setsockopt(SO_RCVLOWAT) failed");
                                                break;
  }

                                rc = recv(sdconn, buffer, sizeof(buffer), 0);
                                if (rc < 0)
                                {
                                                perror("recv() failed");
                                                break;
                                }

                                printf("%d bytes of data were received\n", rc);
                                if (rc == 0 ||
                                                                rc < sizeof(buffer))
                                {
                                                printf("The client closed the connection before all of the\n");
                                                printf("data was sent\n");
                                                break;
                                }

                                rc = send(sdconn, buffer, sizeof(buffer), 0);
                                if (rc < 0)
                                {
                                                perror("send() failed");
                                                break;
                                }

                } while (FALSE);

                if (sd != -1)
                                close(sd);
                if (sdconn != -1)
                                close(sdconn);
}


Tuesday 21 August 2012

Delete empty lines in a file using Vim

:v/\S/d

IPV6 Hostname Resolution in Linx

/* IPV6 resolving host name
arg: hostname*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
#include <errno.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main (int argc, char *argv[])
{
                struct addrinfo *res;
                char ip_addr[INET6_ADDRSTRLEN];
                struct sockaddr_in6 *saddr;
                socklen_t       len ;

                saddr = NULL;

                if( argc != 2 )
                {
                                return -1;
                }

                res = NULL;

                printf("host[%s]\n", argv[1]);

                getaddrinfo(argv[1], NULL ,NULL,&res);

                if ( res != NULL )
                {
                                printf("ai_flags -> %i\n", res->ai_flags) ;
                                printf("ai_family -> %i\n", res->ai_family) ;
                                printf("ai_socktype -> %i\n", res->ai_socktype) ;
                                printf("ai_protocol -> %i\n", res->ai_protocol) ;
                                printf("ai_addrlen -> %i\n", res->ai_addrlen) ;

                                if ( res->ai_family == 2 )
                                {
                                        struct sockaddr_in *saddr = (struct sockaddr_in*)res->ai_addr;
                                        printf("ai_addr hostname ->  %s\n", inet_ntoa( saddr->sin_addr));
                                   }

                                if ( res->ai_family == 10 )
                                {
                                        saddr = (struct sockaddr_in6*)res->ai_addr;

                                        inet_ntop(AF_INET6, &saddr->sin6_addr, ip_addr, INET6_ADDRSTRLEN);
                                    printf("address[%s]\n", ip_addr);
                                 }
                }
                else
                {
                                printf("host is not found\n");
                }

                freeaddrinfo(res);

                return 0 ;
}

Monday 20 August 2012

IPV6 Host Name Resolving in Linux

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char *argv[])
{

                char tmphstbuf [4096];
                size_t hstbuflen  = sizeof (tmphstbuf);
                struct hostent hostinfo_buf = {0,};
                struct hostent *hostresult = NULL;
                int herr ;

                int ret = -1 ;

                size_t len;

                char ip_addr[INET6_ADDRSTRLEN] = {0,};
                 struct sockaddr_in6 addr;

                len = sizeof(tmphstbuf);

                ret = gethostbyname_r(argv[1], &hostinfo_buf, tmphstbuf, len, &hostresult, &herr);


                printf("Addresses:\t");
                inet_ntop(AF_INET6, hostinfo_buf.h_addr_list[0], ip_addr, INET6_ADDRSTRLEN);
                 printf("%s\n", ip_addr);


}

/* Keep add your hostnames in /etc/hosts file */

Saturday 4 August 2012

Simple UDP EchoServer

/*
 * @filename : server.c
 * @brief:  Server Program
 * */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>


#define MAX_LINE 256

int         conn_count=0;
void *HandlingClient(void *);

int main(int argc,char *argv[])
{
        struct sockaddr_in  serv_addr,  client_addr;
        int           sockid, newsockid, len, ret;
         char  buf[MAX_LINE];

        if(argc < 2 )
        {
                printf("usage: %s <port>\n", argv[0]);
                return -1;
        }

        sockid = socket(AF_INET,SOCK_DGRAM, 0);
        if(sockid < 0 )
        {
                printf("Failed to get socket\n");
                return -1;
        }

        serv_addr.sin_family = AF_INET;
        serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
        serv_addr.sin_port = htons(atoi(argv[1]));

        if((bind(sockid,(struct sockaddr*)&serv_addr,sizeof(serv_addr))) != 0)
        {
                printf("Failed to bind\n");
                return -2;
        }

        len = sizeof(client_addr);

        while(1)
        {
                ret = recvfrom(sockid,&buf,MAX_LINE,0, (struct sockaddr*)&client_addr, &len);
                if ( ret == 0 )
                {
                        break;
                }
                else if ( ret < 0 )
                {
                        printf("Error Occurs Err[#%d,%s]\n", errno, strerror(errno) );
                        break;
                }

                if(!strncasecmp(buf,"bye",3))
                {
                        break;
                }

                /* send back to client*/
                if( (ret = sendto(sockid, &buf, ret, 0, (struct sockaddr*)&client_addr, sizeof(client_addr))) <= 0 )
                {
                        printf("Client coultn't send message to server\n");
                        break;
                }
        }

        close(sockid);

        return 0;
}

/*
 *   @filename : client.c
 *     @brief: Client Program
 *     */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MAX_LINE  256


void *SendReceive(void* sockid);

int main(int argc,char *argv[])
{
        struct sockaddr_in  serv_addr, cli_addr ;
        int     sockid;
        char  buf[MAX_LINE],sendbuf[MAX_LINE];
        int   length,ret ;
        socklen_t len;

        if(argc < 3 )
        {
                printf("usage: %s <server-address> <port> \n",argv[0]);
                return -1;
        }

        sockid = socket(AF_INET,SOCK_DGRAM,0) ;
        if(sockid == -1 )
        {
                printf("Failed to get socket\n");
                return -2;
        }

        serv_addr.sin_family = AF_INET ;
        serv_addr.sin_addr.s_addr = inet_addr(argv[1]) ;
        serv_addr.sin_port = htons(atoi(argv[2])) ;

        len = 1;

        while(1)
        {
                memset(buf,0,sizeof(buf));
                if(fgets(buf,MAX_LINE,stdin) == NULL )
                {
                        printf ("received EOF from stdin\n");
                        break;
                }

                length = strlen(buf);

                if( (ret = sendto(sockid, &buf, length, 0, (struct sockaddr*)&serv_addr, sizeof(serv_addr))) <= 0 )
                {
                        printf("Client coultn't send message to server\n");
                        break;
                }

                ret = recvfrom(sockid,&buf,MAX_LINE,0, (struct sockaddr*)&cli_addr, &len);
                if ( ret == 0 )
                {
                        printf("Error Occurs Err[#%d,%s]\n", errno, strerror(errno) );
                        break;
                }
                else if ( ret < 0 )
                {
                        printf("Error Occurs Err[#%d,%s]\n", errno, strerror(errno) );
                        break;
                }
                printf("%s",buf);
        }

        close(sockid);

        return 0;
}

MESSAGE="Echo Program Built Successfully"
MESSAGE1 = " ------------------------- "

CC      = gcc

CFLAGS  = -g -I./include

all:  server client
        @echo $(MESSAGE1)
        @echo $(MESSAGE)
        @echo $(MESSAGE1)

server: server.o
        ${CC} -o $@ server.o

client: client.o
        ${CC} -o $@ client.o

clean:
        -@rm *.o

distclean:  clean
        -@rm server client

Tuesday 31 July 2012

list log files replace particular field

 for i in `ls cdr.30_JUL_2012*`; do perl -e 'while(<>) {@fields=split(/\|/,$_);$fields[5]="hello";for($i=0;$i <= $#fields; $i++){ print "$fields[$i]|";}}' $i > hello.$i; done &

Monday 30 July 2012

Read line from file1 and search string in other files

IFS='/'; while read line ; do { arr=($line); exp="${arr[1]}${arr[2]}"; tmp=`echo $exp | sed -e 's/"//'`; if [ -z $tmp ]; then continue; fi; len=`expr length $tmp`; if [ $len -gt 30 ]; then grep "${arr[1]}/${arr[2]}" mig_proxy.cdr.26_JUL_2012_mig* | grep -v ${arr[0]}; fi } done < cdr.26_JUL_2012* > report.26_JUL_2012 2>&1


--brief: read line from has delimited by "/" and take third splitted str and search string in other files

Friday 27 July 2012

Multiply two intergers using bitwise operator

#include<stdio.h>

void main()
{
    int a,b,result;

    printf("Enter the numbers to be multiplied :\n");

    scanf("%d%d",&a,&b);

    result=0;
    while(b != 0)
    {
        if (b&0x01)
        {
            result=result+a;
        }
        a<<=1;
        b>>=1;
    }
    printf("Result:%d",result);
}

Sunday 26 February 2012

List files not accessed for a week

find ./ -atime +30 -type f -exec rm {} \;

@brief:  find the files in current directory whose are not accessed for 30 days and remove the same.


 

Monday 23 January 2012

get files count and list from all sub directories

#!/bin/bash

DIRS=$(find "$1" -type d)

for d in $DIRS
do
   [ "$d" != "." -a "$d" != ".." ] && echo -e "$d $(ls $d | wc -l)\n$(ls $d)" || :
done

Saturday 7 January 2012

Untar all files in a single directory

---- List all tgz files and untar them and put into specified single directory

for file in `ls -1 mig_proxy.cdr.06_JAN_2012.*`;do tar zxvf $file -C temp/ ; done

 Here temp is where the extracted files will be placed ..