Господа, помогите разобраться с ошибкой.
Суть проблемы: программа слушает трафик,что-то вроде сниффера, так вот функция ioctlsocket() выдает ошибку 10042:Bad protocol option.
А так как опыта работы с винсокетами у меня практически нет, то не могу понять в чем проблема.
Ниже привожу текст программы.
Код: Выделить всё
Global Data
include('Winsock.inc')
sock SOCKET
Prmod ULONG
sopt ULONG
code
err#=WSACleanUP()
clear(PWSAData)
if WSAStartup(s32_Version2_0,address(PWSAData))<>0
Message('Error wsastartup:'&WSAGetLastError())
end
Sock=Createsocket(AF_INET,SOCK_STREAM,IPPROTO_IP)
IF Sock < 0
Message('Error createsocket - '&WSAGetLastError())
ELSE
sopt=True
if setsockopt(Sock,SOL_SOCKET,SO_REUSEADDR,address(sopt),size(sopt))<>0
Message('Setsockopt error - '&WSAGetLastError())
else
s_in.sin_family = AF_INET
s_in.sin_addr.s_addr = INADDR_ANY
end
END
if BindSocket(Sock,address(s_in),Size(s_in))= SOCKET_ERROR Message('Error bindsocket - '&WSAGetLastError())
CloseSocket(Sock)
end
PrMod=1
if ioctlsocket(Sock,SIO_RCVALL,PrMod) <> 0
Message('Error - '&WSAGetLastError()) ! здесь выдет ошибку 10042
CloseSocket(Sock)
err#=WSACleanUP()
end
!здесь буду принимать данные
!
CloseSocket(Sock)
err#=WSACleanUP()
!!!!!!!!!!!!!!!!!!!!!!!!
файл winsock.inc
OMIT('_EndOfInclude_',_WINSOCK_)
_WINSOCK_ EQUATE(1)
INCLUDE('WINDOWS.INC'),ONCE
WSAData GROUP,TYPE
wVersion SHORT
wHighVersion SHORT
szDescription CSTRING(WSADESCRIPTION_LEN + 1)
szSystemStatus CSTRING(WSASYS_STATUS_LEN + 1)
iMaxSockets UNSIGNED
iMaxUdpDg UNSIGNED
lpVendorInfo LONG
END
PWSAData LIKE(WSAData)
in_addr GROUP,TYPE
s_b1 BYTE
s_b2 BYTE
s_b3 BYTE
s_b4 BYTE
S_addr LONG
END
SOCKADDR_IN GROUP,TYPE
sin_family SHORT
sin_port USHORT
!sin_addr LIKE(in_addr),pre(sin)
sin_addr LIKE(in_addr)
sin_zero STRING(8)
END
s_in LIKE(SOCKADDR_IN)
SOCKET_ERROR EQUATE(-1)
s32_Version2_0 EQUATE(1000000010b)
INADDR_ANY EQUATE(0)
SIO_RCVALL EQUATE(98000001h)
SOCKET EQUATE(LONG)
SOCK_STREAM EQUATE(1)
IPPROTO_IP EQUATE(0)
AF_INET EQUATE(2)
SOL_SOCKET EQUATE(0ffffh)
SO_REUSEADDR EQUATE(04h)
MAP
MODULE('WinApi')
WSAStartup PROCEDURE(SHORT wVersionRequested, LONG lpWSAData),SIGNED,PASCAL
WSACleanup PROCEDURE(),SIGNED,PASCAL
WSAGetLastError PROCEDURE(),SIGNED,PASCAL,NAME('WSAGetLastError')
CreateSocket PROCEDURE(SIGNED af, SIGNED type, SIGNED protocol),SOCKET,PASCAL,NAME('socket')
CloseSocket PROCEDURE(SOCKET s),SIGNED,PROC,PASCAL,NAME('closesocket')
ReceiveData PROCEDURE(SOCKET s, LONG lpstrBuffer, SIGNED dwLen, SIGNED flags),SIGNED,PASCAL,NAME('recv')
BindSocket PROCEDURE(SOCKET s, LONG lpname, SIGNED namelen),SIGNED,RAW,PASCAL,NAME('bind')
Listen PROCEDURE(SOCKET s, SIGNED backlog),SIGNED,PASCAL,NAME('listen')
setsockopt PROCEDURE(SOCKET s, SIGNED level, SIGNED optname, LONG lpszOptVal, SIGNED optlen),SIGNED,PASCAL
Ioctlsocket PROCEDURE(SOCKET s,LONG,*ULONG),SHORT,RAW,PASCAL,NAME('IOCTLSOCKET')
END
end
_EndOfInclude_
На компе стоит WinXP Professional SP2,Clarion 6.1.
Заранее благодарна,
Анна.
- Remove From My Forums
-
Question
-
When creating a TcpListener object I am getting error code 10042. Below is the code I am using.
IPHostEntry localMachineInfo = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(localMachineInfo.AddressList[0], System.Convert.ToInt32(tbPort.Text));
TcpListener listener = new TcpListener(localEP);
listener.Start();
When debugging this code I notice that right after listener object is created I see error code 10042 (An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call).
am I missing a configuration setup ?
Answers
-
You are welcome
,
If you feel my replies helped you in your problem. Please mark as Answered.
Best Regards,
Rizwan aka RizwanSharp
I am trying to listen a socket using multicast but it seems that am not using the setsockopt
function well. I have been searching the meaning of the error code 10042 and I have found https://learn.microsoft.com/windows/win32/winsock/windows-sockets-error-codes-2 but I don’t understand the explanation.
Here it is my function where I create a socket to listen a port inside a multicast group:
/* Includes */
#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <cstdlib>
#pragma comment (lib, "Ws2_32.lib")
/* Defines */
#define BUFLEN 1024
#define MULTICAST_GROUP "225.30.8.1"
#define LOCAL_IP "192.168.6.200"
#define DEFAULT_FTI_PORT 8600
/* Structs */
typedef struct {
uint32_t receive_data[BUFLEN]; // receive data
}comm_data_t;
typedef struct {
SOCKET sockfd; // RX socket ID
int long_dir; // size of address
struct sockaddr_in socket_addr; // client socket struct
struct sockaddr_in socket_sender; // sender socket struct
comm_data_t data; // data struct
}socket_t;
socket_t socket_info;
/* Returns 1 if succesfull, 0 otherwise */
uint8_t createSocket(void)
{
WSADATA wsaData;
struct ip_mreq mreq; // multicast
int iResult;
cout << "IP: " << LOCAL_IP << endl;
cout << "MULTICAST GROUP: " << MULTICAST_GROUP << endl;
cout << "PORT: " << DEFAULT_FTI_PORT << endl << endl;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("[SOCKET] WSAStartup failed with error: %dn", iResult);
return 0;
}
memset(&socket_info.socket_addr, 0, sizeof(socket_info.socket_addr));
socket_info.socket_addr.sin_family = AF_INET;
socket_info.socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socket_info.socket_addr.sin_port = htons(DEFAULT_FTI_PORT);
socket_info.long_dir = sizeof(socket_info.socket_sender);
// Create a new socket to make a client connection.
if ((socket_info.sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
printf("[SOCKET] socket() failed! Error code: %ldn", WSAGetLastError());
WSACleanup();
return 0;
}
else
printf("[SOCKET] socket() is OK!n");
if (bind(socket_info.sockfd, (struct sockaddr*) &socket_info.socket_addr, sizeof(socket_info.socket_addr)) < 0)
{
printf("[SOCKET] bind() failed! Error code: %ldn", WSAGetLastError());
return 0;
}
else
printf("[SOCKET] bind() is OK!n");
// Set multicast option
mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
mreq.imr_interface.s_addr = inet_addr(LOCAL_IP);
if ( (setsockopt(socket_info.sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq, sizeof(mreq))) < 0)
{
printf("[SOCKET] setsockopt() failed! Error code: %ldn", WSAGetLastError());
return 0;
}
else
printf("[SOCKET] setsockopt() is OK!n");
return 1;
}
And then I have another function where I read the received data:
/* Returns number of bytes received */
uint8_t readFromSocket(void)
{
int32_t BytesReceived = 0;
/* RECEIVE DATA */
BytesReceived = recvfrom(socket_info.sockfd, (char*) &socket_info.data.receive_data,
BUFLEN, 0,
(struct sockaddr*) &socket_info.socket_sender,
&socket_info.long_dir);
if (BytesReceived < 0)
{
printf("[SOCKET] recvfrom() error %ld.n", WSAGetLastError());
return 0;
}
else
return BytesReceived ;
}
It seems that I am not able to join myself to the multicast group, but I don’t know where I am failing.
I am using UDP protocol, so if I change the parameter of setsockopt
IPPROTO_IP to IPPROTO_UDP, I get the error code 10022.
What do these errors mean and how can I do it correctly?
6
I�m trying to build an application in VB.NET that read GPRS communication protocols, between a GPS Tracker and Server, but when my socket tries to begin receiving the data that came from the tracker I get the error 10042.
Anyone knows what can make this to happen??? And how to fix it???
(I also wrote a client app to prove it with my server side app and it works good)
I’m posting the entery code so you can see it well.
- Imports System
- Imports System.Net
- Imports System.Net.Sockets
- Imports System.Text
- Imports System.Threading
- Imports Microsoft.VisualBasic
- ‘ State object for reading client data asynchronously
- Public Class StateObject
- ‘ Client socket.
- Public workSocket As Socket = Nothing
- ‘ Size of receive buffer.
- Public Const BufferSize As Long = 1078624
- ‘ Receive buffer.
- Public buffer(BufferSize) As Byte
- ‘ Received data string.
- Public sb As New StringBuilder
- End Class ‘StateObject
- Public Class AsynchronousSocketListener
- ‘ Thread signal.
- Public Shared allDone As New ManualResetEvent(False)
- ‘ This server waits for a connection and then uses asychronous operations to
- ‘ accept the connection, get data from the connected client,
- ‘ echo that data back to the connected client.
- ‘ It then disconnects from the client and waits for another client.
- Public Shared Sub Main()
- ‘ Data buffer for incoming data.
- Dim bytes() As Byte = New [Byte](1023) {}
- ‘ Establish the local endpoint for the socket.
- Dim ipHostInfo As IPHostEntry = Dns.Resolve(Dns.GetHostName())
- Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
- Dim localEndPoint As New IPEndPoint(ipAddress, 8000)
- ‘ Create a TCP/IP socket.
- Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
- ‘ Bind the socket to the local endpoint and listen for incoming connections.
- listener.Bind(localEndPoint)
- listener.Listen(100)
- While True
- ‘ Set the event to nonsignaled state.
- allDone.Reset()
- ‘ Start an asynchronous socket to listen for connections.
- Console.WriteLine(«Waiting for a connection…»)
- listener.BeginAccept(New AsyncCallback(AddressOf AcceptCallback), listener)
- ‘ Wait until a connection is made and processed before continuing.
- allDone.WaitOne()
- End While
- End Sub ‘Main
- Public Shared Sub AcceptCallback(ByVal ar As IAsyncResult)
- ‘ Get the socket that handles the client request.
- Dim listener As Socket = CType(ar.AsyncState, Socket)
- ‘ End the operation.
- Dim handler As Socket = listener.EndAccept(ar)
- ‘ Create the state object for the async receive.
- Dim state As New StateObject
- state.workSocket = handler
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
- ‘handler.BeginConnect
- End Sub ‘AcceptCallback
- Public Shared Sub ReadCallback(ByVal ar As IAsyncResult)
- Dim content As String = String.Empty
- ‘ Retrieve the state object and the handler socket
- ‘ from the asynchronous state object.
- Dim state As StateObject = CType(ar.AsyncState, StateObject)
- Dim handler As Socket = state.workSocket
- ‘ Read data from the client socket.
- Dim bytesRead As Integer = handler.EndReceive(ar)
- If bytesRead > 0 Then
- ‘ There might be more data, so store the data received so far.
- state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead))
- ‘ Check for end-of-file tag. If it is not there, read
- ‘ more data.
- content = state.sb.ToString()
- If content.IndexOf(«rn») > -1 Then
- ‘ All the data has been read from the
- ‘ client. Display it on the console.
- Console.WriteLine(«Read {0} bytes from socket. » + vbLf + » Data : {1}», content.Length, content)
- ‘ Echo the data back to the client.
- Send(handler, content)
- Else
- ‘ Not all data received. Get more.
- handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
- End If
- End If
- End Sub ‘ReadCallback
- Private Shared Sub Send(ByVal handler As Socket, ByVal data As String)
- ‘ Convert the string data to byte data using ASCII encoding.
- Dim byteData As Byte() = Encoding.ASCII.GetBytes(data)
- ‘ Begin sending the data to the remote device.
- handler.BeginSend(byteData, 0, byteData.Length, 0, New AsyncCallback(AddressOf SendCallback), handler)
- End Sub ‘Send
- Private Shared Sub SendCallback(ByVal ar As IAsyncResult)
- ‘ Retrieve the socket from the state object.
- Dim handler As Socket = CType(ar.AsyncState, Socket)
- ‘ Complete sending the data to the remote device.
- Dim bytesSent As Integer = handler.EndSend(ar)
- Console.WriteLine(«Sent {0} bytes to client.», bytesSent)
- handler.Shutdown(SocketShutdown.Both)
- handler.Close()
- ‘ Signal the main thread to continue.
- allDone.Set()
- End Sub ‘SendCallback
- End Class ‘AsynchronousSocketListener
May 25 ’10
#1
Я пытаюсь прослушать сокет с помощью многоадресной рассылки, но кажется, что я плохо использую функцию setsockopt
. Я искал значение кода ошибки 10042 и нашел https://learn.microsoft.com/windows/win32/winsock/windows-sockets-error-codes-2, но я не понимаю объяснения.
Вот моя функция, где я создаю сокет для прослушивания порта внутри многоадресной группы:
/* Includes */
#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <cstdlib>
#pragma comment (lib, "Ws2_32.lib")
/* Defines */
#define BUFLEN 1024
#define MULTICAST_GROUP "225.30.8.1"
#define LOCAL_IP "192.168.6.200"
#define DEFAULT_FTI_PORT 8600
/* Structs */
typedef struct {
uint32_t receive_data[BUFLEN]; // receive data
}comm_data_t;
typedef struct {
SOCKET sockfd; // RX socket ID
int long_dir; // size of address
struct sockaddr_in socket_addr; // client socket struct
struct sockaddr_in socket_sender; // sender socket struct
comm_data_t data; // data struct
}socket_t;
socket_t socket_info;
/* Returns 1 if succesfull, 0 otherwise */
uint8_t createSocket(void)
{
WSADATA wsaData;
struct ip_mreq mreq; // multicast
int iResult;
cout << "IP: " << LOCAL_IP << endl;
cout << "MULTICAST GROUP: " << MULTICAST_GROUP << endl;
cout << "PORT: " << DEFAULT_FTI_PORT << endl << endl;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("[SOCKET] WSAStartup failed with error: %dn", iResult);
return 0;
}
memset(&socket_info.socket_addr, 0, sizeof(socket_info.socket_addr));
socket_info.socket_addr.sin_family = AF_INET;
socket_info.socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socket_info.socket_addr.sin_port = htons(DEFAULT_FTI_PORT);
socket_info.long_dir = sizeof(socket_info.socket_sender);
// Create a new socket to make a client connection.
if ((socket_info.sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
printf("[SOCKET] socket() failed! Error code: %ldn", WSAGetLastError());
WSACleanup();
return 0;
}
else
printf("[SOCKET] socket() is OK!n");
if (bind(socket_info.sockfd, (struct sockaddr*) &socket_info.socket_addr, sizeof(socket_info.socket_addr)) < 0)
{
printf("[SOCKET] bind() failed! Error code: %ldn", WSAGetLastError());
return 0;
}
else
printf("[SOCKET] bind() is OK!n");
// Set multicast option
mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
mreq.imr_interface.s_addr = inet_addr(LOCAL_IP);
if ( (setsockopt(socket_info.sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq, sizeof(mreq))) < 0)
{
printf("[SOCKET] setsockopt() failed! Error code: %ldn", WSAGetLastError());
return 0;
}
else
printf("[SOCKET] setsockopt() is OK!n");
return 1;
}
А затем у меня есть еще одна функция, где я читаю полученные данные:
/* Returns number of bytes received */
uint8_t readFromSocket(void)
{
int32_t BytesReceived = 0;
/* RECEIVE DATA */
BytesReceived = recvfrom(socket_info.sockfd, (char*) &socket_info.data.receive_data,
BUFLEN, 0,
(struct sockaddr*) &socket_info.socket_sender,
&socket_info.long_dir);
if (BytesReceived < 0)
{
printf("[SOCKET] recvfrom() error %ld.n", WSAGetLastError());
return 0;
}
else
return BytesReceived ;
}
Кажется, я не могу присоединиться к многоадресной группе, но я не знаю, где я терплю неудачу.
Я использую протокол UDP, поэтому, если я изменю параметр setsockopt
IPPROTO_IP на IPPROTO_UDP, я получу код ошибки 10022.
Что означают эти ошибки и как я могу сделать это правильно?
2 ответа
Вы используете старый набор включаемых файлов. Вместо этого:
#include <windows.h>
#include <winsock.h>
Использовать это:
#include <winsock2.h>
#include <ws2tcpip.h>
И он должен работать как положено.
0
dbush
22 Дек 2022 в 05:48
Я нашел решение самостоятельно.
Я использую другой родной .lib из Windows.
Раньше в моем заголовочном файле у меня было:
#pragma comment (lib, "Ws2_32.lib")
Но теперь я использую другой .lib. Это библиотека, которую я использую прямо сейчас и работает для меня:
#pragma comment (lib, "wsock32.lib")
Я полагаю, что это вопрос дистрибутива моей ОС.
В любом случае большое спасибо за ваши комментарии.
0
Londo
22 Дек 2022 в 11:20
Error 10042 is often a critical system error caused by corrupt and missing registry data. This error should be fixed immediately to prevent further damage to the Windows file system. Download Error 10042 Repair Tool
Your PC Health Report
Scan Time: | Error 10042 Problems: Detected | |||
Operating System: | System Performance: Not Optimized | |||
Screen Resolution: | Registry Errors: Detected | |||
Browser Type: | Danger Level: High |
Error 10042 error symptoms can include slow PC performance, program crashes, system freezes, startup/shutdown problems, and file errors. Risks that can result from not repairing your computer include blue screens, file corruption, and hardware failure.
Fixing Error 10042 is easy. Download and install Advanced System Repair, a Microsoft Windows tool that will analyze your registry for missing, obsolete, and corrupt entries resulting from failed installations, incomplete un-installations, disabled drivers, and spyware applications. Click on the link below for your free download.
Download Error 10042 Repair Tool
*Advanced System Repair will repair Error 10042 and registry data errors on your PC
Instructions
Step 1:
Download & run Advanced System Repair.
Step 2:
Click the «Scan» button.
Step 3:
Click the ‘Fix Errors’ Button to Repair Your PC!