Ошибка an invalid argument was supplied

I want to create a UDP client and server in C# and when I run those, after first send and receive message, this error implement. My code is:

byte[] barray = new byte[1024];
EndPoint ipre = new IPEndPoint(IPAddress.Any, 4040);
socketClint.Bind((IPEndPoint)ipre);
int rc = socketClint.ReceiveFrom(barray, ref ipre);

if (rc > 0)
{
    listBox1.Items.Add("Server: "+ BitConverter.ToInt32(barray,0));
}

This error is about socketClint.Bind((IPEndPoint)ipre); line.

the Error is:

System.Net.Sockets.SocketException was unhandled
HResult=-2147467259
Message=An invalid argument was supplied
Source=System
ErrorCode=10022
NativeErrorCode=10022
StackTrace:
   at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at client1.Form1.getmsg() in c:UsersInspiron 1545DesktopUDPclient1client1Form1.cs:line 38
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

InnerException:

  • Remove From My Forums
  • Question

  • User258730882 posted

    I have an MVC application that I have written in .net Core, a very small part of the application contains a couple API endpoints that will be access via a console application at a set time. None of this is new and I have been using the same code for several
    years to do so, but for whatever reason in Core I am now getting errors. Listed below is the code:

    using (var client = new HttpClient())
    {
    client.BaseAddress = new Uri(«https://localhost:44383/»);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(«application/json»));

    HttpResponseMessage response = await client.GetAsync(«/api/test»);
    if (response.IsSuccessStatusCode)
    {
    var apiresults = await response.Content.ReadAsAsync<List<string>>();
    }
    }

    And the error I receive is:

    An invalid argument was supplied

    //////////////////

    Just to make sure I covered all bases I also wrote the code as such:

    System.Collections.Generic.List<string> apiresults = new System.Collections.Generic.List<string>();
    using (var httpClient = new System.Net.Http.HttpClient())
    {
    using (var response = await httpClient.GetAsync(«https://localhost:44383/api/test»))
    {
    string apiResponse = await response.Content.ReadAsStringAsync();
    apiresults = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.List<string>>(apiResponse);
    }
    }

    // Using RestClient

    private static RestClient client = new RestClient(«https://localhost:44383/api/»);

    RestRequest request = new RestRequest(«Test», Method.GET);
    IRestResponse<List<string>> response = client.Execute<List<string>>(request);

    All three should work, but instead all three give the exact same error «An invalid argument was supplied»

Answers

  • User475983607 posted

    I can’t reproduce the errors.  My test code is below.  FYI, I’m using System.Text.Json; not NewtonSoft.

    Client

    using ConsoleApp1.Models;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using System.Text.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
    
        class Program
        {
            private static HttpClient client;
            static async Task Main(string[] args)
            {
                client = new HttpClient();
    
                List<string> apiresults = await Get();
                foreach (string s in apiresults)
                {
                    Console.WriteLine(s);
                }
            }
    
            private static async Task<List<string>> Get()
            {
    
                client.BaseAddress = new Uri("https://localhost:5001/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
                HttpResponseMessage response = await client.GetAsync("/api/test");
                if (response.IsSuccessStatusCode)
                {
                    return await JsonSerializer.DeserializeAsync<List<string>>(await response.Content.ReadAsStreamAsync());
                }
                else
                {
                    throw new Exception($"Error: {response.StatusCode}");
                }
            }
        }
    }
    

    API

    using Microsoft.AspNetCore.Mvc;
    
    namespace WebApi.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class TestController : ControllerBase
        {
            [HttpGet]
            public string[] Get()
            {
                return new string[] { "Hello", "World" };
            }
        }
    }
    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Monday 12:00 a.m — Friday 11:59 p.m. PST

Fastest response time

Just click the Chat button in
your Clio account!

Monday 12:00 a.m. to Friday 11:59 p.m. PST

North America
1-888-858-2546 (toll free)
604-210-2944

Europe, the Middle East, and Africa
+44-800-433-2546 (UK Freephone)
+44-333-577-2546 (UK Mobile Freephone)

We can also be reached via email at support@clio.com for non-urgent matters. We aim to respond within 24 hours or 1 business day.

Comments

@CTColeman65

dogtopus

added a commit
to dogtopus/pybluez
that referenced
this issue

Jun 17, 2021

@dogtopus

Fixes pybluez#307.

This is not the end of it. We likely need to sweep through the whole _msbt.c codebase and move all LPSTR uses to LPWSTR in order to prevent issues like this from happening again.

rgov

pushed a commit
that referenced
this issue

Jul 21, 2021

@dogtopus

@rgov

Fixes #307.

This is not the end of it. We likely need to sweep through the whole _msbt.c codebase and move all LPSTR uses to LPWSTR in order to prevent issues like this from happening again.

I was working on socket programming. The code was running fine on Python 2 but it was throwing an error while running on Python 3 version.

Error is as follows:

>>py server.py
Traceback (most recent call last):
File "server.py", line 20, in <module>
c, cAddr = s.accept()
File "C:AppDataLocalProgramsPythonPython37-32libsocket.py", line 212, in accept
fd, addr = self._accept()
OSError: [WinError 10022] An invalid argument was supplied

This is the exception thrown by the Operating System while executing socket program on Windows OS.

Solution:

It is mandatory to add listen()

s.listen(20)

Where,

  • “s” is the socket object.
  • 2o is the maximum number of queued connections. You can set any number as per your requirement.

I had missed this line to add in my socket program. Because of this, my program was crashing.

After adding this line of code just before the s.accept(), my issue is solved.

How to debug WinError in Socket Programming?

It is not easy to debug any socket programming errors.

WinError 10022 is for not passing valid arguments to the socket. This is just one example. There are many socket errors you will come across. Each error code has different meaning.  You can check the error codes and their meanings on Official Microsoft website.

To avoid this crash, it is always good practice to add exception handling in any socket program you write.

If you are getting any error in your socket program and not able to fix it, write in the comment. I will help you on my best.

Happy Pythoning!

Python Interview Questions eBook

Aniruddha Chaudhari

I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.


Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Понравилась статья? Поделить с друзьями:
  • Ошибка an exception has occurred что делать
  • Ошибка an error occurred while writing
  • Ошибка an error occurred while starting roblox details httpsendrequest
  • Ошибка an error occurred while sending the request
  • Ошибка access violation at address 00408e8f in module