• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 660
  • Last Modified:

Urgent!! Converting string of chars to char *; char[512] to char *

Hi there, I need help on this immediatley in couple of hours. Pls
I m stuck on this..
I have ..

char buf[512];
char *mybuf;

  I get input(suppose www.yahoo.com) from a client process in buf
  then use getipnodebyname(buf, .....); to get the ip of the hostname in buf

Since getipnodebyname is defined as getipnodebyname(const char *name,....)
 
I cannot use buf directly in place of the *name above. I need to convert it to   char *
 If I hard code the hostname to *mybuf = {"www.yahoo.com"} and use mybuf it works fine ... but I want the client to insert the hostname ... and I cannot change the buf variable to anything else... that is my restriction.

Any help on converting a string of char to a char* will be appreciated ... My clock is counting down ...pls help.
regards,
indianneo


0
indianneo
Asked:
indianneo
  • 11
  • 8
  • 2
1 Solution
 
chunichCommented:
Do you have an error or warning?


Have you tried attaching a null character after the assignment?
mybuf[buf_len] = '/0';



For me I would:

char mybuf[512];
strncpy (mybuf, user_input, 512);

char *mybuf is the same as char mybuf[512];
except the latter defines a size.
0
 
indianneoAuthor Commented:
hi chunic ..thanks for the reply

but it doesn't work... the fucntion im using fails if i do so.

yes it is null terminated...

help pls...
indianneo
0
 
chunichCommented:
What errors are you getting?

And can you should us your code?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
g0rathCommented:
need more info.

since if you have a

char buf[512];

you could pass buf directly to the function
and the compiler will typecast it to a const char * automatically....

are you getting a segfault? or logic error?
0
 
indianneoAuthor Commented:
I am not getting any errors ... no compilatio n errors ...nor warnings
........
.......
  char buf[512];
  char hostnamebuf[512];
  int rc,i;
  struct  hostent *hp, *gethostbyname();
  struct  hostent *a_hp;
  int err,flag=0;
  char **p;
  struct sockaddr_in sockAddr;
  char *mybuf;
..............
..............
.............
/**  get data from  clients and send it back */
  for(;;){
    printf("\n...server is waiting...\n");
    if( (rc=recv(psd, buf, sizeof(buf), 0)) < 0){
      perror("receiving stream  message");
      exit(-1);
    }
    if (rc > 0){
      buf[rc]=NULL;
      printf("\n#rc : %d \n:",rc );
           printf("Received: %s\n",buf);
           /*printf("From TCP/Client: %s:%d\n", inet_ntoa(from.sin_addr),
          ntohs(from.sin_port));
        printf("(Name is : %s)\n", hp->h_name);*/
     
       if (send(psd, buf, rc, 0) <0 )
        perror("sending stream message");
       
      /*getting the ip of the host input by the client*/
****************************************
this is where i wanna use *mybuf because if i use buf it fails ..
if i have *mybuf = {"www.google.com"}; it works fine if i use
mybuf instead of buf below in getipnode....
i tried
      mybuf = (char*)malloc(sizeof(char));
       strcpy(mybuf,buf);
currently what i am doing is below
***************************************
        a_hp = getipnodebyname((char*)(&buf),AF_INET,0,&err);
      if(a_hp == NULL) {
         printf("\nError:"); exit(-1);
      }
      
               for(p=a_hp->h_addr_list; *p != 0; p++) {
        struct in_addr in4;
        char **q;
        
        bcopy(*p,(caddr_t)&in4,hp->h_length);
        (void)printf("%s\t%s",inet_ntop(AF_INET,(void*)&in4,hostnamebuf,sizeof(hostnamebuf)),a_hp->h_name);
      }
    }
...........
...........
...........
help..pls
indianneo
0
 
indianneoAuthor Commented:
hi g0rath
My client gets disconnected at that point and ends up in a repeated loop with an error message saying "sending stream message: Invalid argument"

0
 
g0rathCommented:
these lines are wrong....

mybuf = (char*)malloc(sizeof(char));
strcpy(mybuf,buf);

sizeof(char) is actually one byte....but the len of buf is greater so this will either segfault later, or give incorrect bogus data since you're having a buffer overflow

// Add +1 to hold the '\0' character
// I'm using calloc here as to initialize the memory that mybuf points to being empty
mybuf = (char *)calloc(1, sizeof(char) * rc + 1);
// use strncpy so as to not allow anymore overflow issues...just good practice
strncpy(mybuf,buf,rc);


0
 
g0rathCommented:
as a side note, of your using Linux, that function has been deprecated.
getipnodebyname should no longer be used
use getaddrinfo instead
0
 
indianneoAuthor Commented:
hi g0rath
I tried that It doesn't work ...as  i told you hardcoded mybuf works fine ..
hlp pls ...
indianneo
0
 
g0rathCommented:
sorry that should be, "IF" you use linux...can't type today.
0
 
indianneoAuthor Commented:
well i m using solaris ....
0
 
g0rathCommented:
of course hardcoded mybuf works...

when you declare this:

char *mybuf = "This is a test string";

The compiler is allocating the memory for you and pointing to that string.

char *mybuf;

this by itself just creates a pointer that points to nothing, or is uninitialized.

From that point it needs to be pointed somewhere.
If you are creating the memory then...
You need to initialize memory for it, using either malloc(), calloc() or whatever...
at that point you copy what you want to it using sprintf() strcpy, etc...

Or if you just want to point to someplace that already exists, then just

mybuf = buf;

and your done. You've got a pointer named mybuf that points to the memory stored at buf.
0
 
indianneoAuthor Commented:
hi g0rath
 mybuf = buf; don't work ..still getipnodebyname fails

yes i agree to what you  say ... but what I don't understand is why does the function getipnode..fail though i can still printf the value of mybuf after strncpy and it seems alright .....

help pls...
0
 
g0rathCommented:
"sending stream message: Invalid argument"

that isn't even near your mybuf area...

that is an error with the line:

if (send(psd, buf, rc, 0) <0 )
        perror("sending stream message");


is psd a valid socket?

as in...


int psd;
psd = socket(AF_INET,SOCK_STREAM, 0);
if (psd == -1)
{
    perror("error creating socket:");
    exit(-1);
}
0
 
indianneoAuthor Commented:
yes it is a valid socket from the main function  pls find the code ...as below

main( argc, argv )
int argc;
char *argv[];
{
  int   sd, psd;
  struct   sockaddr_in server;
  struct  hostent *hp, *gethostbyname();
  struct  servent *sp;
  struct sockaddr_in from;
  int fromlen;
  int length;
  char ThisHost[80];
  int pn;
  int childpid;

  sp = getservbyname("echo", "tcp");
/* get TCPServer1 Host information, NAME and INET ADDRESS */

  gethostname(ThisHost, MAXHOSTNAME);
  /* OR strcpy(ThisHost,"localhost"); */

  printf("----TCP/Server running at host NAME: %s\n", ThisHost);
  if  ( (hp = gethostbyname(ThisHost)) == NULL ) {
    fprintf(stderr, "Can't find host %s\n", argv[1]);
    exit(-1);
  }
  bcopy ( hp->h_addr, &(server.sin_addr), hp->h_length);
  printf("    (TCP/Server INET ADDRESS is: %s )\n", inet_ntoa(server.sin_addr));


/** Construct name of socket */
  server.sin_family = AF_INET;
  /* OR server.sin_family = hp->h_addrtype; */
 
  server.sin_addr.s_addr = htonl(INADDR_ANY);
if (argc == 1)
        server.sin_port = htons(0);  
   else  {
        pn = htons(atoi(argv[1]));
        server.sin_port =  pn;
   }
   /*OR    server.sin_port = sp->s_port; */

/** Create socket on which to send  and receive */

  sd = socket (AF_INET,SOCK_STREAM,0);
  /* OR sd = socket (hp->h_addrtype,SOCK_STREAM,0); */
  if (sd<0) {
    perror("opening stream socket");
    exit(-1);
  }
/** this allow the server to re-start quickly instead of fully wait
    for TIME_WAIT which can be as large as 2 minutes */
  reusePort(sd);
  if ( bind( sd, (SA *) &server, sizeof(server) ) < 0 ) {
    close(sd);
    perror("binding name to stream socket");
    exit(-1);
  }

/** get port information and  prints it out */
  length = sizeof(server);
  if ( getsockname (sd, (SA *)&server,&length) ) {
    perror("getting socket name");
    exit(0);
  }
  printf("Server Port is: %d\n", ntohs(server.sin_port));

/** accept TCP connections from clients and fork a process to serve each */
  listen(sd,4);
  fromlen = sizeof(from);
  for(;;){
    psd  = accept(sd, (SA *)&from, &fromlen);
    childpid = fork();
    if ( childpid == 0) {
      close (sd);
      EchoServe(psd, from);
    }
    else{
       printf("My new child pid is %d\n", childpid);
       close(psd);
    }
  }
}

EchoServe(psd, from)
int psd;
struct sockaddr_in from;
{
  char buf[512];
  char hostnamebuf[512];
  int rc,i;
  struct  hostent *hp, *gethostbyname();
  struct  hostent *a_hp;
  int err,flag=0;
  char **p;
  struct sockaddr_in sockAddr;
  char *mybuf;
  /*= {"www.yahoo.com"};*/

  printf("Serving %s:%d\n", inet_ntoa(from.sin_addr),
      ntohs(from.sin_port));
  if ((hp = gethostbyaddr((char *)&from.sin_addr.s_addr,
      sizeof(from.sin_addr.s_addr),AF_INET)) == NULL)
    fprintf(stderr, "Can't find host %s\n", inet_ntoa(from.sin_addr));
  else
    printf("(Name is : %s)\n", hp->h_name);

/**  get data from  clients and send it back */
  for(;;){
    printf("\n...server is waiting...\n");
    if( (rc=recv(psd, buf, sizeof(buf), 0)) < 0){
      perror("receiving stream  message");
      exit(-1);
    }
    if (rc > 0){
      buf[rc]=NULL;
      printf("\n#rc : %d \n:",rc );
      /*     mybuf = (char*)calloc(1,sizeof(char)*rc+1);
      /*for(i = 0;i<=rc;i++) {
      mybuf[i]=buf[i];
      }*/
      mybuf = buf;
            /*strncpy(mybuf,buf,rc);*/
      printf("Received: %s\n",buf);
           /*printf("From TCP/Client: %s:%d\n", inet_ntoa(from.sin_addr),
          ntohs(from.sin_port));
        printf("(Name is : %s)\n", hp->h_name);*/
     

      if (send(psd, buf, rc, 0) <0 )
        perror("sending stream message");
       
     
      printf("\nHere I will print the Ip:");
        a_hp = getipnodebyname(mybuf,AF_INET,0,&err);
      if(a_hp == NULL) {
        flag = 1;
        printf("\nIm in-side a_hp equals NULL:");
      }
      printf("\nIm out-side if:");
      printf("\nh_lenght:: err: %d",err);
      if(flag) printf("\nIt did go in-side:");
      for(p=a_hp->h_addr_list; *p != 0; p++) {
        struct in_addr in4;
        char **q;
        
        bcopy(*p,(caddr_t)&in4,hp->h_length);
        (void)printf("%s\t%s",inet_ntop(AF_INET,(void*)&in4,hostnamebuf,sizeof(hostnamebuf)),a_hp->h_name);
      }
    }
    else {
      printf("TCP/Client: %s:%d\n", inet_ntoa(from.sin_addr),
          ntohs(from.sin_port));
      printf("(Name is : %s)\n", hp->h_name);
      printf("Disconnected..\n");
      close (psd);
      exit(0);
    }
  }
}

indianneo

0
 
g0rathCommented:
so your doing the full client stuff...

socket()
bind()
connect()
send()
recv()

I think we need more code to find the problem
0
 
indianneoAuthor Commented:
the above code is all for server(excpet the port resuse) .. client is as follows

main( argc, argv )
int argc;
char *argv[];
{
  int childpid;
  struct   sockaddr_in server;
  struct   sockaddr_in client;
  struct  hostent *hp, *gethostbyname();
  struct  servent *sp;
  struct sockaddr_in from;
  struct sockaddr_in addr;
  int fromlen;
  int length;
  char ThisHost[80];

  sp = getservbyname("echo", "tcp");

/** get TCPClient1 Host information, NAME and INET ADDRESS */

  gethostname(ThisHost, MAXHOSTNAME);
  /* OR strcpy(ThisHost,"localhost"); */

  printf("----TCP/Cleint running at host NAME: %s\n", ThisHost);
  if  ( (hp = gethostbyname(ThisHost)) == NULL ) {
    fprintf(stderr, "Can't find host %s\n", argv[1]);
    exit(-1);
  }
  bcopy ( hp->h_addr, &(server.sin_addr), hp->h_length);
  printf("    (TCP/Cleint INET ADDRESS is: %s )\n", inet_ntoa(server.sin_addr));

/** get TCPServer1 Host information, NAME and INET ADDRESS */

  if  ( (hp = gethostbyname(argv[1])) == NULL ) {
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    if ((hp = gethostbyaddr((char *) &addr.sin_addr.s_addr,
        sizeof(addr.sin_addr.s_addr),AF_INET)) == NULL) {
      fprintf(stderr, "Can't find host %s\n", argv[1]);
      exit(-1);
    }
  }
  printf("----TCP/Server running at host NAME: %s\n", hp->h_name);
  bcopy ( hp->h_addr, &(server.sin_addr), hp->h_length);
  printf("    (TCP/Server INET ADDRESS is: %s )\n", inet_ntoa(server.sin_addr));

  /* Construct name of socket to send to. */
    server.sin_family = AF_INET;
  /* OR server.sin_family = hp->h_addrtype; */

  server.sin_port = htons(atoi(argv[2]));
  /*OR    server.sin_port = sp->s_port; */

  /*   Create socket on which to send  and receive */

  sd = socket (AF_INET,SOCK_STREAM,0);
  /* sd = socket (hp->h_addrtype,SOCK_STREAM,0); */
 
  if (sd<0) {
    perror("opening stream socket");
    exit(-1);
  }

/** for cs779 assignment #1  */
/*
  client.sin_port = htons(atoi(argv[2]));
  if ( bind( sd, (SA *) &client, sizeof(client) ) ) {
    close(sd);
    perror("binding name to stream socket");
    exit(-1);
  }
*/
/** Connect to TCPServer1 */
  if ( connect(sd, (SA *) &server, sizeof(server)) < 0 ) {
    close(sd);
    perror("connecting stream socket");
    exit(0);
  }
  fromlen = sizeof(from);
  if (getpeername(sd,(SA *)&from,&fromlen)<0){
    perror("could't get peername\n");
    exit(1);
  }
  printf("Connected to TCPServer1: ");
  printf("%s:%d\n", inet_ntoa(from.sin_addr),
      ntohs(from.sin_port));
  if ((hp = gethostbyaddr((char *) &from.sin_addr.s_addr,
      sizeof(from.sin_addr.s_addr),AF_INET)) == NULL)
    fprintf(stderr, "Can't find host %s\n", inet_ntoa(from.sin_addr));
  else
    printf("(Name is : %s)\n", hp->h_name);
 childpid = fork();
 if (childpid == 0) {
   GetUserInput();
 }

/** get data from USER, send it SERVER,
      receive it from SERVER, display it back to USER  */

  for(;;) {
    cleanup(rbuf);
    if( (rc=recv(sd, rbuf, sizeof(buf), 0)) < 0){
      perror("receiving stream  message");
      exit(-1);
    }
    if (rc > 0){
      rbuf[rc]=NULL;
      printf("Received: %s\n", rbuf);
    }else {
      printf("Disconnected..\n");
      close (sd);
      exit(0);
    }


  }
}
cleanup(buf)
char *buf;
{
  int i;
  for(i=0; i<BUFSIZE; i++) buf[i]=NULL;
}

void GetUserInput()
{
for(;;) {
    printf("\nType anything followed by RETURN, or type CTRL-D to exit\n");
    cleanup(buf);
    rc=read(0,buf, sizeof(buf));
    if (rc == 0) break;
    if (send(sd, buf, rc, 0) <0 )
      perror("sending stream message");
  }
  printf ("EOF... exit\n");
  close(sd);
  kill(getppid(), 9);
  exit (0);
}
0
 
indianneoAuthor Commented:
My client gets disconnected at the point server computes the getipnodebyename ...
0
 
indianneoAuthor Commented:
Any help g0rath ...
0
 
g0rathCommented:
/** for cs779 assignment #1  */
/*

http://www.experts-exchange.com/Community_Support/New_to_EE/help.jsp#hi130

We cannot do your homework or assignements...but we can provide clues....

You need to take a step back and debug this step by step...in my tests, the server looks fine...
I didn't get a chance to look at the client, but it would seem there you should test the server
first by hand to make sure it's working as it should....telnet directoy to it to check that out.

Then go through the client and find out whats up with that. You should also try to run on some
extra warning messages for your compiler so that will aid you in finding odd errors.

I'm not sure of what flags work with your compiler but I use -Wall -W to add all the extra warning
messages that in of itself is very helpful. Try and make the compiler to most of the work for you.

Good luck.
0
 
indianneoAuthor Commented:
Yes it is an assignment  ....And Well i was asking for a clue .... if you recall my question ....  and the code that you are looking at is what is already provided .... my question started with converting char string to char * and not how to do or make this work ...

I have been debugging ...but the problem with that is my client terminates after i input a value .... Anyways ... I sincerly appreciate you effort and help and concern.

regards,
indianneo

0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 11
  • 8
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now