473,804 Members | 2,184 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

socket returning gibbarish

Hi, im trying to send text from one pc to anther using C socket
programming, i used send() to send the text, the text i used to send
is a result of a function, the problem is the other side recieves
gibbarish, here are server.c and client.c
------------
server.c
------------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/utsname.h>

#define MYPORT 3490

#define BACKLOG 10

char *sys_info() //the function returns version of system
{
char *computer=mallo c(255*sizeof(ch ar)), *rv=NULL;
struct utsname uts;

if(gethostname( computer, 255) != 0 || uname(&uts) < 0){
fprintf(stderr, "couldnt get host info");
free(computer);
exit(1);
}

rv=uts.version;
return rv;

}
void sigchld_handler (int s)
{
while(wait(NULL ) > 0);
}

int main(void)
{
int sockfd, new_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
struct sigaction sa;
int yes=1;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket" );
exit(1);
}

if (setsockopt(soc kfd,SOL_SOCKET, SO_REUSEADDR,&y es,sizeof(int))
== -1) {
perror("setsock opt");
exit(1);
}

my_addr.sin_fam ily = AF_INET;
my_addr.sin_por t = htons(MYPORT);
my_addr.sin_add r.s_addr = INADDR_ANY;
memset(&(my_add r.sin_zero), '\0', 8);

if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct
sockaddr))

== -1) {
perror("bind");
exit(1);
}

if (listen(sockfd, BACKLOG) == -1) {
perror("listen" );
exit(1);
}

sa.sa_handler = sigchld_handler ; // reap all dead processes
sigemptyset(&sa .sa_mask);
sa.sa_flags = SA_RESTART;
if (sigaction(SIGC HLD, &sa, NULL) == -1) {
perror("sigacti on");
exit(1);
}

while(1) { // main accept() loop
sin_size = sizeof(struct sockaddr_in);
if ((new_fd = accept(sockfd, (struct sockaddr
*)&their_addr,& sin_size)) == -1) {
perror("accept" );
continue;
}
printf("server: got connection from %s\n",

inet_ntoa(their _addr.sin_addr) );
if (!fork()) {
close(sockfd);
if (send(new_fd, sys_info(), strlen(sys_info ()), 0) ==
-1)// this is where i pass the result of the function sys_info() to
send()
perror("ERROR SENDING THE MESSAGE");
close(new_fd);
exit(0);
}
close(new_fd);
}

return 0;
}

-----------
client.c
-----------
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PORT 3490

#define MAXDATASIZE 1000

int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in their_addr;
if (argc != 2) {
fprintf(stderr, "usage: client hostname\n");
exit(1);
}

if ((he=gethostbyn ame(argv[1])) == NULL) { // get the host
info
perror("gethost byname");
exit(1);
}

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket" );
exit(1);
}

their_addr.sin_ family = AF_INET;
their_addr.sin_ port = htons(PORT);
their_addr.sin_ addr = *((struct in_addr *)he->h_addr);
memset(&(their_ addr.sin_zero), '\0', 8);

if (connect(sockfd , (struct sockaddr *)&their_addr,
sizeof(struct sockaddr))
== -1) {
perror("connect ");
exit(1);
}

if ((numbytes=recv (sockfd, buf, MAXDATASIZE-1, 0)) == -1) {
perror("recv");
exit(1);
}

buf[numbytes] = '\0';
printf("Receive d: %s\n",buf);

close(sockfd);

return 0;
}
===
it dosent allways return gibbarish, this is how the result looks like
when sys_info() is passed to send() as a message.
client 127.0.0.1 Received: #2 SM°Ôÿ¿i Feb 20 18:

when i put the code of the function directly into main() and removed
the function sys_info(), it worked fine with these results client 127.0.0.1

Received: #2 SMP Fri Feb 20 18:11:42 GMT 2004
Im sure its obvious but im not that good in C, so if anyone can help
please do.

thanks
Nov 14 '05 #1
10 1521
balzano_1 <ba*******@yaho o.com> scribbled the following:
Hi, im trying to send text from one pc to anther using C socket
programming, i used send() to send the text, the text i used to send
is a result of a function, the problem is the other side recieves
gibbarish, here are server.c and client.c


ISO standard C does not support sockets. Please ask in
comp.unix.progr ammer.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"You can pick your friends, you can pick your nose, but you can't pick your
relatives."
- MAD Magazine
Nov 14 '05 #2
"balzano_1" <ba*******@yaho o.com> wrote in message
news:60******** *************** ***@posting.goo gle.com...
char *sys_info() //the function returns version of system
{
char *computer=mallo c(255*sizeof(ch ar)), *rv=NULL;
struct utsname uts;

if(gethostname( computer, 255) != 0 || uname(&uts) < 0){
fprintf(stderr, "couldnt get host info");
free(computer);
exit(1);
}

rv=uts.version;
return rv;

} .... it dosent allways return gibbarish, this is how the result looks like
when sys_info() is passed to send() as a message.
client 127.0.0.1

Received: #2 SM°Ôÿ¿i Feb 20 18:

when i put the code of the function directly into main() and removed
the function sys_info(), it worked fine with these results
client 127.0.0.1

Received: #2 SMP Fri Feb 20 18:11:42 GMT 2004
Im sure its obvious but im not that good in C, so if anyone can help
please do.


sys_info() returns the address of a variable on its local stack; using this
address after the function returns is undefined behavior.

Also, you have a memory leak -- you malloc memory for char *computer but
it's never freed. In fact, it doesn't appear to even be used.

I'd suggest:

char *sys_info(char *computer, size_t namelen) {
struct utsname uts;
if (gethostname(co mputer, namelen)) {
if (uname(&uts) < 0) {
fprintf(stderr, "couldnt get host info");
exit(1);
} else {
strncpy(compute r, uts.version, namelen);
}
}
return computer;
}

This puts the burden of memory allocation on the caller. To use it, change:

if (send(new_fd, sys_info(), strlen(sys_info ()), 0) == -1)

to:

char buffer[255];
...
sys_info(buffer , sizeof(buffer)) ;
if (send(new_fd, buffer, strlen(buffer), 0) == -1)
S

--
Stephen Sprunk "Stupid people surround themselves with smart
CCIE #3723 people. Smart people surround themselves with
K5SSS smart people who disagree with them." --Aaron Sorkin

Nov 14 '05 #3
balzano_1 wrote:

Hi, im trying to send text from one pc to anther using C socket
programming, i used send() to send the text, the text i used to
send is a result of a function, the problem is the other side
recieves gibbarish, here are server.c and client.c

.... snip ...

Didn't you already post this, and get told it was off-topic here?
At any rate you will find some useful references below.

BTW, when you find a suitable group, try capitalizing the pronoun
'I'.

--
Some useful references:
<http://www.ungerhu.com/jxh/clc.welcome.txt >
<http://www.eskimo.com/~scs/C-faq/top.html>
<http://benpfaff.org/writings/clc/off-topic.html>
<http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)
Nov 14 '05 #4
balzano_1 wrote:

Hi, im trying to send text from one pc to anther using C socket
programming, i used send() to send the text, the text i used to send
is a result of a function, the problem is the other side recieves
gibbarish, here are server.c and client.c
Although the use of sockets is off-topic for c.l.c, the problem is
unrelated to the use of sockets.

[...] char *sys_info() //the function returns version of system
{
char *computer=mallo c(255*sizeof(ch ar)), *rv=NULL;
struct utsname uts;

if(gethostname( computer, 255) != 0 || uname(&uts) < 0){
fprintf(stderr, "couldnt get host info");
free(computer);
exit(1);
}

rv=uts.version;
return rv;

}
You are returning a pointer to a local variable, so using that pointer
results in undefined behavior.

That, and you don't free(computer) on success, so you have a memory
leak.

[...] if (send(new_fd, sys_info(), strlen(sys_info ()), 0) ==
-1)// this is where i pass the result of the function sys_info() to
send()

[...]

Also, once you fix sys_info(), this should be changed to not call it
twice. (What happens on the off chance that different strings are
returned?)

Call it once and save the pointer in a variable. Then pass that variable
to send() and strlen().

--
+-------------------------+--------------------+-----------------------------+
| Kenneth J. Brody | www.hvcomputer.com | |
| kenbrody at spamcop.net | www.fptech.com | #include <std_disclaimer .h> |
+-------------------------+--------------------+-----------------------------+

Nov 14 '05 #5
CBFalconer <cb********@yah oo.com> wrote:

<snip>
BTW, when you find a suitable group, try capitalizing the pronoun
'I'.


Your signature is too long. It should be four lines at most.

Abuse report sent to ab***@worldnet. att.net (violation of RFC 1855).
Nov 14 '05 #6
On 2 May 2004 05:28:56 -0700, in comp.lang.c , so***********@y ahoo.com
(Simon) wrote:
CBFalconer <cb********@yah oo.com> wrote:
BTW, when you find a suitable group, try capitalizing the pronoun 'I'.


Your signature is too long. It should be four lines at most.

Abuse report sent to ab***@worldnet. att.net (violation of RFC 1855).


Prat.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #7
Simon <so***********@ yahoo.com> spoke thus:
Your signature is too long. It should be four lines at most.
Abuse report sent to ab***@worldnet. att.net (violation of RFC 1855).


Amazing.

*plonk*

--
Christopher Benson-Manica | I *should* know what I'm talking about - if I
ataru(at)cybers pace.org | don't, I need to know. Flames welcome.
Nov 14 '05 #8
Simon wrote:
CBFalconer <cb********@yah oo.com> wrote:

<snip>
BTW, when you find a suitable group, try capitalizing the pronoun
'I'.

Your signature is too long. It should be four lines at most.

Abuse report sent to ab***@worldnet. att.net (violation of RFC 1855).


CBFalconer's signature is 5 lines long, and RFC 1855 just says:
| - If you include a signature keep it short. Rule of thumb
| is no longer than 4 lines. Remember that many people pay for
| connectivity by the minute, and the longer your message is,
| the more they pay.

Best regards,
Robert Bachmann
--
Ro************* @rbdev.net |) |)
http://rb.rbdev.net |\.|).
Nov 14 '05 #9

In article <82************ **************@ posting.google. com>, so***********@y ahoo.com (Simon) writes:

Your signature is too long. It should be four lines at most.

Abuse report sent to ab***@worldnet. att.net (violation of RFC 1855).


Network Working Group
Request For Comments: 1855
FYI: 28
Category: Informational
...
This memo does not specify an Internet standard of any kind.

RFC 1855 is not a standard, nor on the standards track. As such
it cannot be "violated". (I suggest you read FYI 1, RFC 1150,
before accusing people of "violating" FYIs.)

Further:

- The signature length statement in 1855 is qualified as a "rule of
thumb". If 1855 specified compliance conditions, which it does not,
it wouldn't even be a conditional-compliance condition.

- The signature length statement in 1855 appears in section 2.1.1,
covering one-to-one email messages. There is no equivalent
statement in section 3.1.1, covering Usenet.

--
Michael Wojcik mi************@ microfocus.com

Dude, it helps to be smart if you're gonna be mean. -- Darby Conley
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
11782
by: Bryan Olson | last post by:
Here's the problem: Suppose we use: import socket f = some_socket.makefile() Then: f.read() is efficient, but verbose, and incorrect (or at least does not play will with others);
9
2483
by: Phil Jenson | last post by:
I am try to evaluate the most efficient method of handling thousands of simultaneous TCP connects each of which remain connected to the server for hours and pass a small amount of data usually once a minute. The data received is logged in a SQL Server database. The only method I have found of reading each socket requires a thread for each connection which blocks waiting for data. This appears to be very inefficient as it will result in...
3
2207
by: ferbar | last post by:
Hello all, This may sound pretty basic stuff.. but I'm working on a socket example whose client seems to work fine, but the server doesn't send to the client the expected result. The problem is that I want to trace what the server socket is doing, but I'm unable to see any of my fprintf or printf stuff. Please take a look to the example:
13
2652
by: coloradowebdev | last post by:
i am working on basically a proxy server that handles requests via remoting from clients and executes transactions against a third-party server via TCP. the remoting site works like a champ. my problem is executing the transactions against the remote server and returning the response to the remoting client. i can open the socket fine and, if i am executing one transaction at a time, everything works great. it's when my proxy server...
2
15336
by: djc | last post by:
I read a network programming book (based on framework 1.1) which indicated that you should 'never' use the RecieveTimeout or the SendTimeout 'socket options' on TCP sockets or you may loose data. I now see the socket.RecieveTimeout 'property' in the visual studio 2005 help documentation (framework 2.0) and it has example of it being used with TCP socket. This propery is also listed as 'new in .net 2.0'. 1) is the socket.RecieveTimeout...
0
4759
by: phplasma | last post by:
Hey, I am currently attempting to implement a multi-threaded C# socket, using SSL (.pem file/certification/private key combo) server using Visual Studio C# Express. I have successfully made the client application establish a connection, and send data, which appears in plain, de-crypted text on the server - this works.
1
3187
by: mirandacascade | last post by:
I noticed the following lines from the connect() method of the HTTPConnection class within httplib: for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res This led me to the docs that describe the socket.getaddrinfo() method: http://www.python.org/doc/2.4.1/lib/module-socket.html
6
15617
by: billiejoex | last post by:
Hi there. I'm setting up test suite for a project of mine. situations, if the socket is closed on the other end or not. I noticed that I can "detect" such state if a call to socket.read() returns 0 but it seems a little poor to me. :-\ Is there a reliable way to test such socket 'state'?
10
7410
by: Hendrik van Rooyen | last post by:
While doing a netstring implementation I noticed that if you build a record up using socket's recv(1), then when you close the remote end down, the recv(1) hangs, despite having a short time out of 0.1 set. If however, you try to receive more than one char, (I tested with 3, did not try 2), then when you shut the remote end down you do not get a time out, but an empty string - the normal end of file, I suppose. Has anybody else seen...
0
9594
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10341
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10089
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5530
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.