I use this code to send an integer from my Java Client to my Java Server
int n = rand.nextInt(50) + 1;
DataOutputStream dos = new DataOutputStream(_socket.getOutputStream());
dos.writeInt(n);
And i read it in the server with this code
DataInputStream din = new DataInputStream(socket.getInputStream());
int ClientNumber= din.readInt();
System.out.println(ClientNumber);
ClientNumber++;
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeInt(ClientNumber);
String randomString= getRandomValue(10,20);
dos.writeUTF(randomString);
It work perfectly but now i want to write a C client
I tried this code
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERVEURNAME "localhost" // adresse IP de mon serveur
int to_server_socket = -1;
void main ( void )
{
char *server_name = SERVEURNAME;
struct sockaddr_in serverSockAddr;
struct hostent *serverHostEnt;
long hostAddr;
long status;
char buffer[512];
bzero(&serverSockAddr,sizeof(serverSockAddr));
hostAddr = inet_addr(SERVEURNAME);
if ( (long)hostAddr != (long)-1)
bcopy(&hostAddr,&serverSockAddr.sin_addr,sizeof(hostAddr));
else
{
serverHostEnt = gethostbyname(SERVEURNAME);
if (serverHostEnt == NULL)
{
printf("gethost rate\n");
exit(0);
}
bcopy(serverHostEnt->h_addr,&serverSockAddr.sin_addr,serverHostEnt->h_length);
}
serverSockAddr.sin_port = htons(8071);
serverSockAddr.sin_family = AF_INET;
/* creation de la socket */
if ( (to_server_socket = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("creation socket client ratee\n");
exit(0);
}
/* requete de connexion */
if(connect( to_server_socket,
(struct sockaddr *)&serverSockAddr,
sizeof(serverSockAddr)) < 0 )
{
printf("demande de connection ratee\n");
exit(0);
}
/* envoie de donne et reception */
int value = htons( 4 );
write( to_server_socket, &value, sizeof( value ) );
printf(buffer);
}
but it don't work. I use Eclipse for to compile the java code and running the Server and xcode for the C code ( the Client ) but i don't think that the problem is there
Edit:
I got an error on the server
java.net.SocketException: Broken pipe at
java.net.SocketOutputStream.socketWrite0(Native Method) at
java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:115) at
java.io.DataOutputStream.writeInt(DataOutputStream.java:182) at
ServiceRequest.run(ServiceRequest.java:36) at
java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
I think it's because i the server wait for an integer but it isn't ...?
Two things that jump out at me in this statement...
write(to_server_socket,"4",4);
1) "4" is not an integer, it's a null terminated string (well, okay, it is an integer, but it's not what you "meant" to do me thinks)
2) You are sending the value in host-byte-order which may or may not be the same as network-byte-order
int value = htons( 4 );
write( to_server_socket, &value, sizeof( value ) );
Beyond that, however, the "broken pipe" error from the java socketWrite()would tend to indicate that your sending side (the C application) has closed the socket and your java side is still trying to write to it.
Your C client code is opening the socket, writing to it then immediately printing a buffer you never filled with anything and exiting the program. As soon as the program exits, the socket you created for it is closed, thus the "broken pipe" error in your Java server. You need to read a reply from the server...
int value = htonl( 4 );
int reply = 0;
if( send( to_server_socket, &value, sizeof( value ), 0 ) != sizeof( value ) )
{
printf( "socket write failed: %s", strerror( errno ) );
exit( -1 );
}
if( recv( to_server_socket, &reply, sizeof( reply ), MSG_WAITALL ) != sizeof( reply ) )
{
printf( "socket read failed: %s", streror( errno ) );
exit( -1 )
}
printf( "got reply: %d\n", ntohl( reply ) );
On a separate note... you indicate that you receive 262144 on the server... is that before or after the changes I suggested? 262144 is 0x00040000 -- so... you did get 4, just not where you expected to receive it. So, you're using 32 bit ints (I should have realized that) which means you want to use htonl() and ntohl() instead of the htons() and ntohs() which are short integer conversions.
Related
I am using the following code. This is the code after device discovery works fine.
BluetoothDevice btdevice = adapter.getRemoteDevice(device.getAddress());
btdevice.fetchUuidsWithSdp();
ParcelUuid[] bt = btdevice.getUuids();
for (ParcelUuid x:bt) {
try {
BluetoothSocket socket = btdevice.createRfcommSocketToServiceRecord(x.getUuid());
socket.connect();
if (socket.isConnected())
break;
} catch (IOException e) {
e.printStackTrace();
}
}
On PC side I am running Ubuntu 18.04 and BlueZ version 5.48.
The server side code is:
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
sdp_session_t *register_service()
{
uint32_t svc_uuid_int[] = { 0x00000000,0x00000000,0x00000000,0x00000000 };
uint8_t rfcomm_channel = 11;
const char *service_name = "Remote Host";
const char *service_dsc = "What the remote should be connecting to.";
const char *service_prov = "Your mother";
uuid_t root_uuid, l2cap_uuid, rfcomm_uuid, svc_uuid;
sdp_list_t *l2cap_list = 0,
*rfcomm_list = 0,
*root_list = 0,
*proto_list = 0,
*access_proto_list = 0;
sdp_data_t *channel = 0, *psm = 0;
sdp_record_t *record = sdp_record_alloc();
// set the general service ID
sdp_uuid128_create( &svc_uuid, &svc_uuid_int );
sdp_set_service_id( record, svc_uuid );
// make the service record publicly browsable
sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
root_list = sdp_list_append(0, &root_uuid);
sdp_set_browse_groups( record, root_list );
// set l2cap information
sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
l2cap_list = sdp_list_append( 0, &l2cap_uuid );
proto_list = sdp_list_append( 0, l2cap_list );
// set rfcomm information
sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
channel = sdp_data_alloc(SDP_UINT8, &rfcomm_channel);
rfcomm_list = sdp_list_append( 0, &rfcomm_uuid );
sdp_list_append( rfcomm_list, channel );
sdp_list_append( proto_list, rfcomm_list );
// attach protocol information to service record
access_proto_list = sdp_list_append( 0, proto_list );
sdp_set_access_protos( record, access_proto_list );
// set the name, provider, and description
sdp_set_info_attr(record, service_name, service_prov, service_dsc);
int err = 0;
sdp_session_t *session = 0;
// connect to the local SDP server, register the service record, and
// disconnect
session = sdp_connect( BDADDR_ANY, BDADDR_LOCAL, SDP_RETRY_IF_BUSY );
err = sdp_record_register(session, record, 0);
// cleanup
//sdp_data_free( channel );
sdp_list_free( l2cap_list, 0 );
sdp_list_free( rfcomm_list, 0 );
sdp_list_free( root_list, 0 );
sdp_list_free( access_proto_list, 0 );
return session;
}
int main(int argc, char **argv)
{
struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
char buf[1024] = { 0 };
char str[1024] = { 0 };
int s, client, bytes_read;
sdp_session_t *session;
socklen_t opt = sizeof(rem_addr);
session = register_service();
s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
loc_addr.rc_family = AF_BLUETOOTH;
loc_addr.rc_bdaddr = *BDADDR_ANY;
loc_addr.rc_channel = (uint8_t) 11;
bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
listen(s, 1);
client = accept(s, (struct sockaddr *)&rem_addr, &opt);
ba2str( &rem_addr.rc_bdaddr, buf );
fprintf(stderr, "accepted connection from %s\n", buf);
memset(buf, 0, sizeof(buf));
bytes_read = read(client, buf, sizeof(buf));
if( bytes_read > 0 ) {
printf("received [%s]\n", buf);
}
sprintf(str,"to Android.");
printf("sent [%s]\n",str);
write(client, str, sizeof(str));
close(client);
close(s);
sdp_close( session );
return 0;
}
I have tried with channels 1 and 11. I tried using the UUID I provided in C code and also the UUIDs by using btdevice.getUuids(); and the Uuids that I am receiving are
0000110a-0000-1000-8000-00805f9b34fb
00001108-0000-1000-8000-00805f9b34fb
0000110b-0000-1000-8000-00805f9b34fb
0000110e-0000-1000-8000-00805f9b34fb
00001112-0000-1000-8000-00805f9b34fb
00000000-0000-1000-8000-00805f9b34fb
00000000-0000-1000-8000-00805f9b34fb
The android code is able to pair to linux device but I think that't the system implementation of Ubuntu and not my code because it's not printing anything.
On android side it gives the following error on the line:
socket.connect();
java.io.IOException: read failed, socket might closed or timeout, read
ret: -1
Please someone tell me what can I do? it has already taken one full day of my time.
I am connecting to an device with opening an socket.
To get incoming data I perform an readaction on the InputStream in a different thread.
When I take away the electricity of the peer device I am connected to, my InputStream doesn't recognize the loss of connection.
This is my code to wait for input:
StringBuilder sb = new StringBuilder();
String result = "";
int c;
try
{
log.info( "waiting for data..." );
while ( ( ( c = inputStream.read() ) >= 0 ) )
{
if ( c == -1 )
{
log.info( "is -1" );
}
/*
* TODO: <LF> Can't always be the delimiter to define the end of an message. This should be
* parameterized.
*/
if ( c == 0x0a /* <LF> */ )
{
result = sb.toString();
sb.delete( 0, sb.length() );
}
else if ( c != 0x0d /* <CR> */ )
{
sb.append( (char) c );
}
if ( !result.isEmpty() )
{
log.info( getName() + ": received message: " + result );
listener.MessageReceived( result.getBytes() );
result = "";
}
}
log.info( "stream ended" );
disconnect();
listener.closed();
}
catch ( IOException | ResourceException e )
{
try
{
log.info( "in catch block" );
disconnect();
listener.closed();
throw new ResourceException( "An error occured during the receiving of a message for the device, or connection timed out.", e );
}
catch ( ResourceException e1 )
{
e1.printStackTrace();
}
}
This is inside of an JCA connector if that information is for use in any case.
To my knowledge the InputStream receives -1 when the Stream is interrupted and normally he should jump to my stream endedlog but it doesn't happen.
why doesn't it recognize that the connection can't be available, since the remote peer is powered off?
As you say, you don't want a timeout because you need to wait for the peer even if it doesn't send for hours. Barring special measures, there is no difference between a peer that doesn't send for hours and a peer that has been turned off. As long as no packets are sent, it's impossible to detect the difference.
You can do one thing to ensure that packets are sent: you can turn on the SO_KEEPALIVE socket option using the method Socket.setKeepAlive(true).
The problem is that you can't control from Java how often the keep-alive probes are sent. This typically depends on settings in your operating system kernel.
Still, it will allow you to detect a dead (or unreachable) peer quicker than "never".
A 'read timeout', as suggested by #Kayaman, IS the usual method of implementing a heartbeat. You need a 'timingOut' boolean, initialized to false. Whenever ANY data is received, data or heartbeat poll reply, set it to false. Upon read timeout check the 'timingOut' flag. If false, send a poll request and set 'timingOut' to true. If true, close socket and take your 'connection lost' action/s.
No need for a separate thread. No wasteful polling if data is being transferred often.
I am writing a Java interposer to modify network communication related system calls. Basically, I want to modify the IP and port of the intended recipient.
The code works correctly on my laptop, but on university PC, it gives a stack smashing error as:
*** stack smashing detected ***: java terminated
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(__fortify_fail+0x45)[0xb7702dd5]
/lib/i386-linux-gnu/libc.so.6(+0xffd8a)[0xb7702d8a]
/home/mwaqar/vibe/ldinterposer_2.so(+0x28e4)[0xb77c98e4]
/home/mwaqar/vibe/ldinterposer_2.so(connect+0x9c5)[0xb77c9093]
/usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/libnet.so(+0xceff)[0x8b226eff]
/usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/libnet.so(Java_java_net_PlainSocketImpl_socketConnect+0x4c1)[0x8b227c51]
The relevant code (interposition of connect system call) is as follows:
int connect(int fd, const struct sockaddr *sk, socklen_t sl)
{
struct sockaddr_in *lsk_in = (struct sockaddr_in *) sk;
struct sockaddr_in6 *lsk_in6 = (struct sockaddr_in6 *) sk;
struct sockaddr_in addr4;
unsigned int len;
int nbytes, oport, tport, ret, i;
char ip_address[30];
char buffer[1024];
char tempBuffer[1024];
if((lsk_in->sin_family == AF_INET) || (lsk_in->sin_family == AF_INET6))
{
if(lsk_in->sin_family == AF_INET)
{
oport = ntohs(lsk_in->sin_port);
memcpy(&addr4.sin_addr.s_addr, &lsk_in->sin_addr.s_addr, sizeof(addr4.sin_addr.s_addr));
}
else if(lsk_in->sin_family == AF_INET6)
{
oport = ntohs(lsk_in6->sin6_port);
memcpy(&addr4.sin_addr.s_addr, lsk_in6->sin6_addr.s6_addr+12, sizeof(addr4.sin_addr.s_addr));
}
memset(buffer, '\0', sizeof(buffer));
sprintf(buffer, "%s%c%s%c%i", NAT_VM_CONNECT_RULE, NAT_VM_DELIMITER, (char *)inet_ntoa(addr4.sin_addr), NAT_VM_DELIMITER, oport);
nbytes = send(sock, buffer, strlen(buffer), 0);
if(DEBUG_MODE)
fprintf(stdout, "[LD_INTERPOSER] Sent[%s]\n", buffer);
memset(buffer, '\0', sizeof(buffer));
nbytes = recv(sock, buffer, sizeof(buffer), 0);
fprintf(stderr, "[LD_INTERPOSER] Received CONNECT [%s]\n", buffer);
memset(ip_address, '\0', sizeof(ip_address));
int pos = strrchr(buffer, NAT_VM_DELIMITER) - buffer;
strncpy(ip_address, buffer, pos);
ip_address[pos] = '\0';
tport = atoi(buffer + pos + 1);
if(lsk_in->sin_family == AF_INET)
{
lsk_in->sin_addr.s_addr = inet_addr(ip_address + 7);
lsk_in->sin_port = htons(tport);
}
else if(lsk_in->sin_family == AF_INET6)
{
inet_pton(AF_INET6, ip_address, &(lsk_in6->sin6_addr));
lsk_in6->sin6_port = htons(tport);
}
fprintf(stderr, "[LD_INTERPOSER] IP[%s], Port[%d] for VM[%s]\n", ip_address, tport, vm_ip);
}
int my_ret = real_connect(fd, sk, sl);
fprintf(stderr, "Done\n");
return my_ret;
}
Here, sock is a socket that I have initialized in "constructor" of the shared library.
The program works correctly and prints Done. On the last (return) line, it gives the stack smashing error. I have no idea what is causing this.
I suspect that strrcr returns NULL in the line
int pos = strrchr(buffer, NAT_VM_DELIMITER) - buffer;
Then pos will be huge, and the following lines will read and write invalid addresses.
Always check the return value of functions (especially when they're run on data received from outside your program).
Also, as I wrote in my comment, never use sprintf. I can't tell if it fails, because I don't know what's NAT_VM_CONNECT_RULE. Even if you counted the bytes and know you're OK, you should still be careful and use snprintf instead.
I'm trying to have a connection between a Java server and a C++ client. But when I read the data in my client I always have the same strange character (’). I tried to change the encoding in both side but nothing work.
Here is my Java code :
public class Serveur
{
public static void main(String[] args) throws Exception
{
final int PORT = 13370;
try
{
ServerSocket service= new ServerSocket(PORT);
Socket connection = service.accept();
PrintWriter pw = new PrintWriter(connection.getOutputStream());
String s = Integer.toString(5);
while(true)
{
pw.print(s.getBytes("UTF-8"));
pw.flush();
pw.close();
}
connection.close();
}
}
I also tried to use an OutputStream, a DataOutputStream and a BufferedOutputStream.
And here is the C++ code :
int main(int argc, char* argv[])
{
WSADATA WSAData;
WSAStartup(MAKEWORD(2,0), &WSAData);
SOCKET sock;
SOCKADDR_IN sin;
char buffer[512];
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_family = AF_INET;
sin.sin_port = htons(13370);
sock = socket(AF_INET,SOCK_STREAM,0);
if(connect(sock, (SOCKADDR*)&sin, sizeof(sin)) != SOCKET_ERROR)
{
cout<<"connection"<<endl;
if(recv(sock, buffer, sizeof(buffer), 0) != SOCKET_ERROR)
{
string s = buffer;
wchar_t *pwchello = L"Hi";
wchar_t *pwc = (wchar_t *)malloc( sizeof( wchar_t ));
char *pmbhello = buffer;
int i = mbstowcs(pwc,pmbhello, MB_CUR_MAX);
cout << i << endl;
cout<<"cout : "<<pwc<<endl;
cout <<buffer<<endl;
printf("printf : %s\n", buffer);
cout << "wsagetlasterror() : "<<WSAGetLastError();
closesocket(sock);
WSACleanup();
free(m_pBuffer);
}
return 0;
}
As you can see, I tried different solution but without success.
Thanks in advance, and sorry for my english it may be not very good
You are mixing up lots of different encoding conversions and I/O strategies. You should try out the following simplified version:
if(connect(sock, (SOCKADDR*)&sin, sizeof(sin)) != SOCKET_ERROR)
{
cout << "connection" << endl;
// the result of 'recv()' is either SOCKET_ERROR or
// the number of bytes received. don't though away
// the return value.
const int result = recv(sock, buffer, sizeof(buffer), 0);
if(result != SOCKET_ERROR)
{
// use length (in bytes) returned by 'recv()'
// since buffer is not null terminated.
string s(buffer,result);
// 's' is in UTF-8 no converstion to wide strings
// should be necessary.
cout << "message: '" << s << "'." << endl;
}
closesocket(sock);
}
WSACleanup();
However, note that the standard output is in the current code page and usually UTF-8 is not the default code page. Outputing Unicode data to the console in windows requires a few other library calls to configure.
recv does not turn its destination buffer into null-terminated string. It fills in a number of bytes in the buffer, but does not append a 0.
You need top do this (with error checking, of course):
ssize_t bytesRead = recv(buffer, ...);
string str(buffer, bytesRead);
Also, be aware that recv does not guarantee that something sent in one call gets received in one call (unless you're doing UDP).
You're only allocating room for a single wchar_t here:
wchar_t *pwc = (wchar_t *)malloc( sizeof( wchar_t ));
You also assign buffer to string s, but never seem to use s
I have been having the same problem since last night. Finally figured out that encoding is not recognized by my server (written in C). Therefore, I changed in my client
someOutputStream.writeUTF(someSillyString);
to
someOutputStream.write(someSillyString.getBytes());
This way, I did not even need to typecast on the server side.
I hope I'll not get a tonne of messages that's dump question. I really tried to find out where is the problem but I don't know why this works on one linux and cause segmentation fault on other linux. So when I run it on computer number one it works fine but when I run it on comuputer number two it cause segmentation fault and I get message SIGSEGV.
Computer number one has config:
cat /etc/issue get: Debian GNU/Linux 5.0
uname -a get: Linux eryx2 2.6.34.4servgs #3 SMP Sun Aug 22 00:38:18 CEST 2010 i686 GNU/Linux
Computer number two has config:
cat /etc/issue get: Ubuntu 11.10
uname -a get: Linux ubuntu 3.0.0-15-generic #25-Ubuntu SMP Mon Jan 2 17:44:42 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux
I enclose code of my application.
1.I run the server - ok
2.I run the client
3.Client sends message to server
4.Server try to recieve message from server and it cause segmentation fault
But this problem is only on Ubuntu when I run it on first computer i've specified it works ok.
I also build resp. compile source codes on each system.
server:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include <unistd.h>
#include <signal.h>
#include <stdlib.h>
int sendMessage(char* msg, int socket){
int length = strlen(msg);
int ret;
ret = write(socket, msg, length);
return ret;
}
int readLine(void *vptr, size_t maxlen, int sockd) {
int n, rc;
char c, *buffer;
buffer = vptr;
for ( n = 1; n < maxlen; n++ ) {
if ( (rc = read(sockd, &c, 1)) == 1 ) {
*buffer++ = c;
if ( c == '\n' )
break;
}
else if ( rc == 0 ) {
if ( n == 1 )
return 0;
else
break;
}
}
*buffer = 0;
return n;
}
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket( AF_INET, SOCK_STREAM, 0 );
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = inet_addr( "127.0.0.1" );
server_address.sin_port = htons( 10000 );
server_len = sizeof( server_address );
if( bind( server_sockfd, ( struct sockaddr *)&server_address, server_len ) != 0 )
{
perror("oops: server-tcp-single");
exit( 1 );
}
listen( server_sockfd, 5 );
signal( SIGCHLD, SIG_IGN );
while( 1 )
{
char ch;
printf( "server wait...\n" );
client_len = sizeof( client_address );
client_sockfd = accept( server_sockfd, ( struct sockaddr *)&client_address, &client_len );
printf( "Connected client from %s\n", inet_ntoa( client_address.sin_addr) );
if( fork() == 0 )
{
char retezec[20];
readLine(retezec, 20, client_sockfd);
printf( "Klient sent : %s\n", retezec );
printf( "Server sends : %s\n", retezec );
sendMessage(retezec, client_sockfd);
close( client_sockfd );
exit (0 );
}
else
close( client_sockfd );
}
}
client
import java.io.*;
import java.net.*;
class clientTCP
{
private static PrintWriter pw;
private static BufferedReader br;
private static void sendToServer(String msg) {
try
{
pw.println(msg);
//System.out.println(msg);
System.out.println("Klient poslal: " + msg);
}
catch (Exception e)
{
// System.out.println("e.Message");
}
}
private static String recieveFromServer() {
String msg = "Chyba";
try
{
msg = br.readLine();
//System.out.println(msg);
System.out.println("Klient prijal: " + msg);
}
catch (Exception e)
{
System.out.println("Selhalo prijimani zpravy zpravy!");
//System.out.println(e.Message);
}
return msg;
}
public static void main(String argv[]) throws Exception
{
Socket socket = new Socket("127.0.0.1", 10000);
InetAddress adresa = socket.getInetAddress();
System.out.print("Pripojuju se na : "+adresa.getHostAddress()+" se jmenem : "+adresa.getHostName()+"\n" );
pw = new PrintWriter(socket.getOutputStream(), true);
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
sendToServer("ahoj\n");
String message = recieveFromServer();
//System.out.println("Message Received: " + message);
socket.close();
}
}
Thanks.
Edited java and gcc versions:
first computer Debian:
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) Server VM (build 16.3-b01, mixed mode)
gcc version 4.3.2 (Debian 4.3.2-1.1)
second computer Ubuntu
java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02, mixed mode)
gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3)
Edit: Problem solved trought dicusion and googling
so I'm adding changes it may help somebody with similar problem.
There were couple problems in Server:
instead of
int server_len, client_len;
I should use
socklen_t str_len, client_len;
Then instead of this (which was the cause of segmentation fault):
printf( "Connected client from %s\n", inet_ntoa( client_address.sin_addr) );
I should use function inet_ntop cause I found that inet_ntoa deprecated.
Cause of seg fault was that I use %s so as arg of printf is expected char *
this is the better solution and I hope also clear.
char str[INET_ADDRSTRLEN];
inet_ntop(AF_INET,&(client_address.sin_addr), str, INET_ADDRSTRLEN);
printf( "Connected client from %s\n", str );
I didn't know what with this question, cause I get good answers trouht comments and my work.
So I at least added fixes needed to solve problem.
I would make sure you always set \0 at the end. You have a return 0 which the caller ignores. This means if the char[] doesn't have a \0 byte already in array you could get a seg fault.
i meet the same problem. it's because you fail to include
#include <arpa/inet.h>
which result a implicit declare whille compiling the code. the implicit declare method always return an int instread of other types(like char *).
seg fault when
printf( "Connected client from %s\n", inet_ntoa(
client_address.sin_addr) );
because the inet_ntoa() returns a address and was converted to 0xffffffffef7dde20, which is out of bounds. the inet_ntoa's return value was treated as a 32 bit int.
you fix your problem with inet_ntop, not because of inet_ntop is the solution, if you use the return value of inet_ntop as the argument of printf, you still get a segment fault.