The OpenNET Project / Index page

[ новости /+++ | форум | теги | ]




Версия для распечатки Пред. тема | След. тема
Новые ответы [ Отслеживать ]
socket+n00b, !*! PxEL, 19-Окт-09, 21:39  [смотреть все]
Доброго всем!
Решил освоить, однако лезут ошибки в талмутном примере.
представлюсь:
uname -a
Linux myhost 2.6.31-ARCH #1 SMP PREEMPT Tue Oct 13 13:36:23 CEST 2009 i686 Intel(R) Celeron(R) M processor 1.60GHz GenuineIntel GNU/Linux


/***********************************************************************
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC  *
* Copyright (C) 2001 by New Riders Publishing                          *
* See COPYRIGHT for license information.                               *
***********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

/* Read text from the socket and print it out.  Continue until the
   socket closes.  Return non-zero if the client sent a "quit"
   message, zero otherwise.  */

int server (int client_socket)
{
  while (1) {
    int length;
    char* text;

    /* First, read the length of the text message from the socket.  If
       read returns zero, the client closed the connection.  */
    if (read (client_socket, &length, sizeof (length)) == 0)
      return 0;
    /* Allocate a buffer to hold the text.  */
    text = (char*) malloc (length);
    /* Read the text itself, and print it.  */
    read (client_socket, text, length);
    printf ("%s\n", text);
    /* Free the buffer.  */
    free (text);
    /* If the client sent the message "quit", we're all done.  */
    if (!strcmp (text, "quit"))
      return 1;
  }
}

int main (int argc, char* const argv[])
{
  const char* const socket_name = argv[1];
  int socket_fd;
  struct sockaddr_un name;
  int client_sent_quit_message;

  /* Create the socket.  */
  socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0);
  /* Indicate this is a server.  */
  name.sun_family = AF_LOCAL;
  strcpy (name.sun_path, socket_name);
  bind (socket_fd, &name, SUN_LEN (&name));
  /* Listen for connections.  */
  listen (socket_fd, 5);

  /* Repeatedly accept connections, spinning off one server() to deal
     with each client.  Continue until a client sends a "quit" message.  */
  do {
    struct sockaddr_un client_name;
    socklen_t client_name_len;
    int client_socket_fd;

    /* Accept a connection.  */
    client_socket_fd = accept (socket_fd, &client_name, &client_name_len);
    /* Handle the connection.  */
    client_sent_quit_message = server (client_socket_fd);
    /* Close our end of the connection.  */
    close (client_socket_fd);
  }
  while (!client_sent_quit_message);

  /* Remove the socket file.  */
  close (socket_fd);
  unlink (socket_name);

  return 0;
}

при компиляции имею:


socket-server.c: In function 'main':
socket-server.c:53: warning: passing argument 2 of 'bind' from incompatible pointer type
/usr/include/sys/socket.h:115: note: expected 'const struct sockaddr *' but argument is of type 'struct sockaddr_un *'
socket-server.c:65: warning: passing argument 2 of 'accept' from incompatible pointer type
/usr/include/sys/socket.h:214: note: expected 'struct sockaddr * __restrict__' but argument is of type 'struct sockaddr_un *'

запуск делаю:
./socket-server /tmp/socket

клиентской программой отправляю сообщение ./socket-client ./tmp "hi"
и получаю на сервере "Segmentation fault"

клиентский код, наврятли, но если нужен:


/***********************************************************************
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC  *
* Copyright (C) 2001 by New Riders Publishing                          *
* See COPYRIGHT for license information.                               *
***********************************************************************/

#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

/* Write TEXT to the socket given by file descriptor SOCKET_FD.  */

void write_text (int socket_fd, const char* text)
{
  /* Write the number of bytes in the string, including
     NUL-termination.  */
  int length = strlen (text) + 1;
  write (socket_fd, &length, sizeof (length));
  /* Write the string.  */
  write (socket_fd, text, length);
}

int main (int argc, char* const argv[])
{
  const char* const socket_name = argv[1];
  const char* const message = argv[2];
  int socket_fd;
  struct sockaddr_un name;

  /* Create the socket.  */
  socket_fd = socket (PF_LOCAL, SOCK_STREAM, 0);
  /* Store the server's name in the socket address.  */
  name.sun_family = AF_LOCAL;
  strcpy (name.sun_path, socket_name);
  /* Connect the socket.  */
  connect (socket_fd, &name, SUN_LEN (&name));
  /* Write the text on the command line to the socket.  */
  write_text (socket_fd, message);
  close (socket_fd);
  return 0;
}


google послал гулять далеко на восток :(
  • socket+n00b, !*! PxEL, 22:15 , 19-Окт-09 (1)
    поправлюсь:
    клиентом отправляю ./socket-client /tmp/socket "hi"
  • причём здесь гугль, !*! Вова, 23:30 , 19-Окт-09 (2)
    зачем гугль?

    gcc -g ./server.c -o server
    gcc -g ./client.c -o client
    ulimit -c unlimited
    ./server /tmp/socket
    ./client /tmp/socket hi
    gdb ./server core*

    • причём здесь гугль, !*! PxEL, 20:38 , 21-Окт-09 (3)
      >зачем гугль?
      >
      >gcc -g ./server.c -o server
      >gcc -g ./client.c -o client
      >ulimit -c unlimited
      >./server /tmp/socket
      >./client /tmp/socket hi
      >gdb ./server core*

      спасибо за ответ
      то что выдало:

      warning: Can't read pathname for load map: Input/output error.
      Reading symbols from /lib/libc.so.6...(no debugging symbols found)...done.
      Loaded symbols for /lib/libc.so.6
      Reading symbols from /lib/ld-linux.so.2...(no debugging symbols found)...done.
      Loaded symbols for /lib/ld-linux.so.2
      Core was generated by `./server /tmp/socket'.
      Program terminated with signal 11, Segmentation fault.
      #0  0xb7721553 in strlen () from /lib/libc.so.6

    • причём здесь гугль, !*! PxEL, 21:22 , 21-Окт-09 (4)
      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>

      int main ()
      {
      char* h="hello";
      int d;
      d = strlen (h) + 1 ;
      printf("%s \n %s \n %s \n",h,&d,d);
      }

      результат:
      hello

      Segmentation fault

      может кроме клёпки чего-то другого не хватает?

      • причём здесь гугль, !*! аноним, 21:42 , 21-Окт-09 (6)
        >int main ()
        >{
        >char* h="hello";

        const char *

        >int d;
        >d = strlen (h) + 1 ;
        >printf("%s \n %s \n %s \n",h,&d,d);
        >результат:
        >hello
        >
        >Segmentation fault

        Потрудитесь объяснить что вы хотели сказать этим кодом.

        Почему адрес числа и число у вас выводятся как строки? Для печати указателей есть %p, для чисел %d со товарищи. И вообще, зачем вам адрес d?




Партнёры:
PostgresPro
Inferno Solutions
Hosting by Hoster.ru
Хостинг:

Закладки на сайте
Проследить за страницей
Created 1996-2024 by Maxim Chirkov
Добавить, Поддержать, Вебмастеру